🛠 Asservir un servo moteur avec un potentiomètre (PWM)
Objectives
Control a standard servo motor (pulse-width signal) from the Leonardo using the Servo library, driven by a potentiometer. You will identify the 7 PWM pins on the board (3, 5, 6, 9, 10, 11, 13, using 8-bit PWM via analogWrite) — the Servo library generates pulses using hardware timers on its side — and most importantly, the power supply rules for a servo.
Hardware
- 1 Arduino Leonardo + micro-USB cable
- 1 micro servo (SG90/MG90S type)
- 1 potentiometer on A0 (5V/GND)
- External 5-6 V power supply for the servo if using multiple servos or under load; never from the 3V3 pin (50 mA maximum)
Complete code
#include <Servo.h>
Servo monServo;
const uint8_t POT_PIN = A0;
const uint8_t SERVO_PIN = 9; // broche PWM (3, 5, 6, 9, 10, 11 ou 13)
void setup {
monServo.attach(SERVO_PIN); // impulse ~50 Hz, 1 a 2 ms
}
void loop {
int brut = analogRead(POT_PIN); // 0..1023
int angle = map(brut, 0, 1023, 0, 180); // 0..180 degres
monServo.write(angle);
delay(15);
}
Expected verification
The servo arm follows the potentiometer between its two mechanical stops (~0° and ~180°). The motor buzzes slightly when stationary: this is normal for a standard servo. Power the servo from the board's 5V pin for a single small SG90; as soon as it heats up or the board restarts due to insufficient current, switch to an external power supply with a common GND.
Common errors
- Powering the servo from 3V3: this pin is limited to 50 mA, while a servo under peak load requires much more; the board resets.
- No common ground: without GND connected between the external power supply and the Leonardo, the servo vibrates or does not respond.
- Current per pin: official values differ (40 mA on the store page versus 10 mA in tech-specs.yml; check the ATmega32u4 datasheet before designing) — never power a servo directly from a digital pin.
- Forgetting that the Servo library uses timers: on the ATmega32u4, certain PWM channels (
analogWriteon 3/5/6/9/10/11/13) and other libraries may cause timer conflicts. - Non-PWM pin for
analogWrite: LEDs blink on/off instead of varying in brightness; only pins 3/5/6/9/10/11/13 are PWM.
Other tutorials for this board
- Faire clignoter la LED intégrée (broche 13)
- Bouton et console série : Serial (USB) vs Serial1 (broches 0/1)
- Lire un capteur analogique : potentiomètre et ADC 10 bits
- Clavier USB : taper du texte avec la bibliothèque Keyboard
- Souris USB : déplacer le curseur avec la bibliothèque Mouse
- Programmer aux registres : interruption Timer/Counter1
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino