Understanding the component
This page documents the software library. For how a servo motor works as hardware (motor, gearbox, signal, power), see the reference The servo motor.
Driving a servo motor to a position from code
Servo / ESP32Servo library
Reference for the Servo library (and ESP32Servo for the ESP32): concepts, main functions and differences between the two.
The Servo library (and ESP32Servo for ESP32-type microcontrollers) controls a servo motor by automatically generating the PWM signal that matches an angle. It saves you from configuring timers by hand or writing pulse-generation code.
The PWM signal is a periodic electrical pulse whose width sets the angle of the servo motor:
These pulses are sent every 20 ms (a 50 Hz frequency). The library generates this signal for you from the requested angle.
Servo.attach(pin)Binds a servo motor to a pin of the microcontroller.
Servo monServo;
monServo.attach(9); // Attaches a servo motor to pin D9
Servo.write(angle)Moves the servo motor to a given angle (between 0° and 180°).
monServo.write(90); // Moves the servo to 90°
Servo.writeMicroseconds(value)Finer control, by sending a pulse width directly (in microseconds).
monServo.writeMicroseconds(1500); // Pulse for 90° (centre position)
Servo.detach()Disconnects the servo motor from the pin, freeing the resources.
monServo.detach(); // Frees the pin used by the servo motor
The API is identical; only the low-level implementation changes.
| Servo (Arduino) | ESP32Servo | |
|---|---|---|
| PWM generation | Built-in hardware timers | LEDC module (LED PWM Controller), stable signals |
| Compatible pins | Specific PWM pins only | Almost all, except reserved ones (RX/TX, GPIO0…) |