🛠 Piloter un micro-servo moteur
Objectives
Control a micro-servo (such as the SG90) using the Servo library: the servo expects a 20 ms frame where a 1 to 2 ms pulse defines the angle. We program a 0-180° sweep and discuss proper power supply (the Nano's 5 V is sufficient for ONE small servo, never for multiple).
Hardware
- 1 × classic Arduino Nano (ATmega328P)
- 1 × SG90 or MG90S micro-servo
- External 5 V power supply recommended if using multiple servos; common ground with the Nano is mandatory
- >
Complete code
// Balayage servo 0-180 degres sur la broche 9
#include <Servo.h>
Servo myservo;
uint8_t angle = 0;
bool sens = true;
void setup {
myservo.attach(9); // signal sur broche 9
myservo.write(0);
Serial.begin(9600);
}
void loop {
angle += sens ? 5 : -5; // pas de 5 degres
if (angle >= 180) sens = false;
if (angle <= 0) sens = true;
myservo.write(angle); // 0..180
Serial.println(angle);
delay(50); // vitesse du balayage
}
Expected verification
The servo arm sweeps regularly from 0° to 180° and returns, smoothly, without excessive jitter or constant buzzing. The serial monitor displays the increasing then decreasing angle setpoint. When stopped at a position, the servo holds its torque without trembling in a loop.
Common errors
- Powering multiple servos from the Nano's 5 V: current spikes cause the ATmega328P to brown out (reset loop); power the servo separately and connect the grounds.
- Forgetting the common ground between the external power supply and the Nano: the servo vibrates in all directions, with random positioning.
- Using attach on a pin occupied by SoftwareSerial or another peripheral: interrupt conflict, corrupted PWM signal.
- Forcing the servo mechanically beyond 180°: the servo's internal potentiometer hits its limit and the motor overheats.
Other tutorials for this board
Code examples for this board
buzzer-melodie.inoArduinoservo-sweep.inoArduinoultrason-hcsr04.inoArduinolcd-i2c.inoArduinoeeprom-contre.inoArduinosommeil-watchdog.inoArduino