🛠 Piloter un servo moteur avec le PWM et un potentiomètre

Arduino Micro · intermediaire · Schéma : IMG-micro-intermediaire-3-micro-pwm-servo.svg — Servomoteur alimenté par une source externe 5V reliée à GND commun, signal sur la broche 9 d'une Arduino Micro, potentiomètre sur A0, alimentation Vin 7-12V conseillée

Objectives

Control a servo motor using the Servo library on a PWM pin of the Micro (3, 5, 6, 9, 10, 11, or 13) and command it with a potentiometer, while properly managing power: the Micro is powered via Vin (7-12 V) or USB, and the 3V3 pin provides only 50 mA.

Hardware

Complete code

// Servo sur broche PWM 9, commande par potentiometre sur A0.
#include <Servo.h>

const uint8_t KNOB = A0;
const uint8_t PIN_SERVO = 9;   // broche PWM : 3,5,6,9,10,11,13
Servo monServo;

void setup {
  monServo.attach(PIN_SERVO);   // signal PWM 50 Hz
  Serial.begin(9600);
}

void loop {
  int brut = analogRead(KNOB);          // 0..1023
  uint8_t angle = map(brut, 0, 1023, 0, 180);
  monServo.write(angle);
  Serial.println(angle);
  delay(20);
}

Expected verification

The servo arm follows the potentiometer between 0 and 180 degrees, without jerking. At the end of the range, the servo buzzes slightly then goes silent once the angle is held.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials