🛠 Piloter un servo moteur avec le PWM et un potentiomètre
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
- 1 Arduino Micro
- 1 SG90/MG90S type servo motor (orange signal, red +5V, brown GND)
- 1 10 kΩ potentiometer on A0 (wiper to A0, ends to 5V/GND)
- External 5 V power supply for the servo if using multiple servos, or Vin 7-12 V on the Micro; common GND is mandatory
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
- Powering a large servo directly from the Micro's 5 V pin while connected via USB: current spikes cause the board to restart (the USB polyfuse cuts off at 500 mA); use a separate power supply with a common GND.
- Forgetting the common GND between the servo and the Micro: the servo vibrates or does not move.
- Connecting the servo to 3V3: this pin is limited to 50 mA, which is insufficient.
- Using a non-PWM pin for the signal: the Servo library works on other pins as well, but sticking to a PWM pin simplifies troubleshooting.
- Expecting a standard analogWrite signal: the Servo library emits calibrated pulses; do not mix it with analogWrite on the same pin.
Other tutorials for this board
- Faire clignoter la LED embarquée (et comprendre les LED TX/RX)
- Lire un bouton avec une résistance de pull-up interne
- Lire un capteur analogique sur le convertisseur 10 bits
- Transformer le Micro en clavier USB (HID) avec bouton de sécurité
- Pont Serial vers Serial1 : passerelle USB vers TTL
- Sortir des sentiers : registres AVR et interruption externe
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino