🛠 Piloter un micro-servo avec la bibliothèque Servo
Objectives
Control a micro-servo (SG90 type) in position using the Servo library, sweeping through a few predefined angles. Important reminder about the Nano Every: PWM is available on pins 3, 5, 6, 9, 10 — we will use pin 9. The megaAVR core remaps the timers, so libraries that hijack a timer (older servo drivers or bit-bang RF encoders) may require an updated version.
Hardware
- 1 × Arduino Nano Every
- 1 × micro-servo SG90 (or MG90S)
- External 5 V power supply recommended if using multiple servo motors (the USB 5 V rail heats up quickly with 2 servo motors)
- Male-to-female jumper wires, micro-USB cable
Complete code
// Balayage de positions sur servo, broche 9 (broche PWM valide)
#include <Servo.h>
Servo myservo;
const uint8_t BROCHE_SERVO = 9;
const uint8_t positions[] = {0, 45, 90, 135, 180};
uint8_t index = 0;
uint32_t tPrecedente = 0;
void setup {
myservo.attach(BROCHE_SERVO); // impulsions 1 a 2 ms
Serial.begin(9600);
Serial.println(F("Servo pret"));
}
void loop {
if (millis - tPrecedente >= 1000) {
tPrecedente = millis;
myservo.write(positions[index]);
Serial.print(F("angle="));
Serial.println(positions[index]);
index = (index + 1) % (sizeof(positions) / sizeof(positions[0]));
}
}
Expected verification
The servo arm moves every second to 0°, 45°, 90°, 135°, 180°, then starts over. The serial monitor displays the current angle. At the end of the travel range, the servo growls slightly (command out of range): this is normal with write at the limits.
Common errors
- Servo on a non-PWM pin (11 by reflex from Uno): the Servo library generates its own pulses, but keep a clean PWM pin for readability and compatibility.
- Powering a large servo directly from the 5 V pin: voltage drops, board resets — use a separate power supply with a common ground.
- Forgetting the common ground between the external power supply and the board: the servo vibrates or does not respond.
attachon a pin already used by other timer libraries: on megaAVR, check for timer conflicts if you combine servo + PWM + buzzer.- Servo jittering in position: intermittent command; pace the
writecalls withmillisas shown above rather than in everyloop.
Other tutorials for this board
Code examples for this board
multi-serie.inoArduinoadc-filtre.inoArduinointerrupt-bouton.inoArduinonvm-consignes.inoArduinosommeil-every.inoArduinowatchdog-secours.inoArduino