🛠 Piloter un servo avec le PWM (LEDC)
Objectives
Control a micro-servo using the Servo library (built on the ESP32-S3's LEDC PWM controller) and make it sweep from 0 to 180°. Understand the power supply: the board has no 5 V pin, while a standard servo operates at 4.8–6 V.
Hardware
- 1 × Arduino Nano ESP32
- 1 × SG90 micro-servo: signal on D9, 5 V external power supply (batteries or regulator), common ground with the board is mandatory
- >
Complete code
#include <Servo.h>
Servo balai;
const uint8_t PIN_SERVO = 9; // D9, PWM via LEDC dans le core Arduino
void setup {
Serial.begin(115200);
balai.attach(PIN_SERVO); // PWM 50 Hz, standard servo
}
void loop {
for (int a = 0; a <= 180; a += 15) { balai.write(a); delay(300); }
for (int a = 180; a >= 0; a -= 15) { balai.write(a); delay(300); }
}
Expected verification
The servo arm sweeps 0 → 180 → 0° in a smooth loop. Powered from an external 5 V source with a common ground, the movement is complete without the board restarting or the USB LED flickering.
Common errors
- Servo powered by the board: there is no 5 V pin (VBUS only passes through USB) and the GPIOs deliver a maximum of 40 mA — a servo draws too much current.
- No common ground between the servo power supply and the board: the servo vibrates, hums, or does not respond.
- Direct connection to the board's 3.3 V: under-voltage, negligible torque, brown-out, and restarts.
- Confusing write (angle) and writeMicroseconds (pulse width): write(1500) is clamped to 180°.
Other tutorials for this board
Code examples for this board
connexion-wifi.inoArduinopoint-acces.inoArduinoble-capteur.inoArduinoneoled-rgb.inoArduinoadc-12bits.inoArduinopreferences.inoArduino