Lessons · Lesson A2 · Actuators and motors · 35 min
Servos and PWM
Understand PWM and duty cycle, then command a servo to an angle with 1 to 2 ms pulses, with its own power supply. About 35 minutes, with a slider you can move.
A motor that knows where it is
A normal small motor spins when you give it power, and you have no idea how far it went. A servo is different. It packs a motor, a gearbox and a way of checking its own position into one small box [3]. You do not tell it “spin”; you tell it “go to this angle”, and it goes there.
How do you say an angle with one wire? Not with a voltage, but with the length of a pulse: the servo expects a pulse roughly every 20 milliseconds, and the length of that pulse sets the angle [2].
In this lesson you will:
- learn PWM, the on-off trick that carries that message,
- see how pulse length becomes angle,
- move a servo with a button, with a safe power supply.
PWM and duty cycle
PWM stands for pulse width modulation. A digital pin can only be on or off, but if it switches on and off over and over, you can control how long it stays on each time. That time is the pulse width [1].
Two numbers describe the pattern:
- the frequency: how many on-off cycles per second. The duration of one cycle, the period, is its inverse [1]. At 50 cycles per second, one period is 1 / 50 = 0.02 s = 20 ms.
- the duty cycle: the share of each period that the signal is on [1]. Always on is 100 %, on half of the time is 50 %.
For an LED, you set the duty cycle and the eye averages the flashes into a brightness between off and full [1]. A common Arduino board’s PWM runs at about 500 Hz, so each period lasts about 2 ms [1]. On those boards, analogWrite() uses a scale of 0 to 255: 255 means always on, 127 about half the time [1].
A servo is different: it does not average, it measures the pulse. A 1.5 ms pulse in a 20 ms period is a duty cycle of 1.5 / 20 = 7.5 %. The servo reacts to those 1.5 ms, not to the average [2].
Try it in the widget below: drag the slider and see the pulse, the duty bar and the horn angle move together.
Simulation of a typical servo, not your servo.
pulse 1.5 ms, duty 7.5 %, angle about 90°
ledcWrite(18, 1228);
Inside the usual range: 1.0 to 2.0 ms.
This is the starting state: the controls need JavaScript.
From pulse length to angle
Here is the rule for a typical hobby servo [2][3]:
| Pulse length | Where the servo goes |
|---|---|
| about 1 ms | one end of its travel (angle zero) |
| about 1.5 ms | the middle |
| about 2 ms | the other end (about 180°) |
The pulse repeats roughly every 20 ms [2].
Where the picture stops. These numbers are a guide, not a law. The end points vary, and many servos only turn about 170° [2]. A seller’s page for a micro servo warns that the usual 1 to 2 ms may not give the full 180°; it suggests trying 0.75 to 2.25 ms, but warns that pushing the pulses further could break the servo [3]. So start with 1 to 2 ms, and widen only a little at a time. If the servo buzzes or strains at one end, back off at once. There are also “continuous” servos that spin all the way round [2]; they do not follow this table, so read the sheet of yours.
The sketch below uses map(): it turns an angle between 0 and 180 into a pulse between 1000 and 2000 microseconds (a microsecond is a millionth of a second, so 1000 µs = 1 ms).
Power: its own supply
A servo pulls real current. It draws quite a lot, especially as the motor starts, and the sudden demand can drop the voltage of the board so far that it resets [4]. A board that restarts when the servo moves is a sign of this [4].
So the rule is simple:
- The servo gets its own supply, one that matches what its sheet says. (Adafruit lists one micro servo for 3 to 6 V, with 4.8 V nominal [3].) For that servo, a holder of 4 NiMH AA cells with an on/off switch gives 4.8 V (see lesson E4). Four alkaline cells give about 6 V, and a fresh pack can exceed 6 V, which is at or above the top of that range, so prefer 4 NiMH cells (4.8 V). Never take the servo’s power from the board’s
3V3pin, and never connect the + of the servo supply to any pin of the board. - Join the grounds. The ground of the servo supply goes to a
GNDpin of the ESP32, so that the signal and the supply share the same zero. - The signal wire goes to a GPIO pin: here GPIO 18. This wire carries no power, only the pulses.
- A large capacitor across the servo’s supply is a known fix when voltage drops cause resets [4]. The Adafruit servo lesson suggests 470 µF or more [4]. A capacitor that big is usually an electrolytic one: it has a stripe marking its − leg, which goes to the supply’s −, and its voltage rating must be above the supply voltage (10 V minimum, 16 V gives a comfortable margin). We will look at capacitors in lesson C1.
Do not power the servo from a pin at all, and do not move on if it makes the board reset: fix the supply first.
Command the servo
Fix the servo horn to the shaft after the first run, not before: the sketch begins by moving to the middle. Wire it as in the diagram: signal on GPIO 18, its own supply, grounds joined, the button on GPIO 27 (other leg to GND).
The ESP32 has hardware for generating PWM, the LEDC peripheral, mostly designed for controlling the brightness of LEDs but usable for other PWM signals [5]. So we do not need an extra library: two functions are enough.
// Tinker Mission, lesson A2: command a hobby servo with PWM (50 Hz, pulses of 1 to 2 ms)
// Wiring (the servo has its OWN power: never take it from the board):
// Servo signal wire -> GPIO 18
// Servo power wire -> + of a separate supply that suits your servo (see its sheet; e.g. 4 NiMH AA = 4.8 V)
// Servo ground wire -> - of that supply
// (your servo's sheet or plug tells you which of its three wires is which)
// Ground of that supply -> a GND pin of the ESP32 (the grounds must be joined)
// Button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// Each press moves the servo to the next position: 0, 90, 180, 90 degrees, and so on.
// This uses the board's own PWM hardware (LEDC), so no extra library is needed.
const int SERVO_PIN = 18;
const int BUTTON_PIN = 27;
const int SERVO_FREQ = 50; // 50 pulses per second: one every 20 ms
const int SERVO_BITS = 14; // duty counted in steps of 1/16384 of the 20 ms
const unsigned long PERIOD_US = 1000000UL / SERVO_FREQ; // 20000 microseconds
const int MIN_US = 1000; // pulse for 0 degrees (1 ms)
const int MAX_US = 2000; // pulse for 180 degrees (2 ms)
// Some servos can go a little further with 750 to 2250 us. Widen these two numbers
// only a little at a time, and stop at once if the servo buzzes against its end stop.
const int positions[] = {0, 90, 180, 90}; // angles to visit, in degrees
const int POSITION_COUNT = sizeof(positions) / sizeof(positions[0]);
int positionIndex = 0;
bool wasPressed = false;
// Turn an angle (0 to 180) into a pulse length in microseconds.
int angleToPulseUs(int angle) {
return map(angle, 0, 180, MIN_US, MAX_US);
}
// Send the pulse length to the PWM hardware, as a duty value.
void setServoPulseUs(int pulseUs) {
uint32_t maxDuty = (1UL << SERVO_BITS) - 1; // 16383, the top value: always on
uint32_t duty = (uint32_t)pulseUs * maxDuty / PERIOD_US; // share of the 20 ms
ledcWrite(SERVO_PIN, duty);
}
void moveTo(int angle) {
int pulseUs = angleToPulseUs(angle);
setServoPulseUs(pulseUs);
Serial.print("angle ");
Serial.print(angle);
Serial.print(" deg -> pulse ");
Serial.print(pulseUs);
Serial.println(" us");
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
ledcAttach(SERVO_PIN, SERVO_FREQ, SERVO_BITS); // pin, frequency, resolution (bits)
moveTo(90); // start in the middle
}
void loop() {
bool pressed = (digitalRead(BUTTON_PIN) == LOW);
if (pressed && !wasPressed) { // just pressed (not held)
positionIndex = (positionIndex + 1) % POSITION_COUNT;
moveTo(positions[positionIndex]);
}
wasPressed = pressed;
delay(20); // also hides contact bounce
}
Download the sketch folder (.zip)
Open the Serial Monitor at 115200 baud. Each press moves the servo and prints the angle and the pulse.
How to read it:
ledcAttach(pin, frequency, resolution)sets up the PWM on that pin. You choose the frequency and a resolution in bits (1 to 14, or up to 20 on the classic ESP32) [5]. We choose 50 Hz and 14 bits.- A resolution of 14 bits means the 20 ms period is cut into 16,384 steps, each about 1.2 µs long. The duty value counts how many steps the signal is on.
ledcWrite(pin, duty)sets that duty value [5].duty = pulse in µs × steps / 20,000 µsis the whole conversion. For 1500 µs that gives 1228 steps (the sketch drops the decimals) in a 16,384-step period: 7.5 %.angleToPulseUs()usesmap()to go from angle to pulse. ThensetServoPulseUs()converts the pulse to duty.- The button works by edge: the servo moves once per press, not once per loop. The
wasPressedvariable remembers the last reading.
Try your own changes
Change one thing, upload, observe.
- Other positions. Edit the
positionslist: try {0, 45, 90, 135, 180}. Make surepositionIndexwraps around: it uses% POSITION_COUNT. - Find the ends of your servo. Change
MIN_USto 900, then 800, andMAX_USto 2100, then 2200, one step at a time. Stop as soon as the servo strains or buzzes at the end of its travel [3]. - A slow sweep. Replace the button with a loop that moves one degree every 15 ms, from 0 to 180 and back. Why is
delay(15)fine here, and when would it not be (see K4)? - Read the duty. Print
dutyinsetServoPulseUs(). Do the numbers match 5 %, 7.5 % and 10 % of 16,384?
When it does not work
- Nothing moves. Check the signal wire on GPIO 18 and that the supply is on. Check that the servo’s supply ground reaches a
GNDpin of the ESP32. - The servo twitches or the board resets. The supply is too weak or shared with the board [4]. Give the servo its own supply. A big capacitor on the servo supply can help [4].
- It moves a little and stops, or only works from some USB ports. Same cause: voltage dips under load [4].
- It buzzes or strains at an end. The pulses ask for more travel than the servo has [2][3]. Narrow
MIN_USandMAX_US. - It never reaches the full 180°. Many servos only turn about 170° [2]. Widen the pulses a little, as in the changes above.
- “ledcAttach was not declared” when you compile. Your esp32 board package is too old. In the Boards Manager, update “esp32 by Espressif Systems” to version 3 or later [5].
- Nothing in the Serial Monitor. Set it to 115200 baud, the same as
Serial.begin(115200).
Check yourself
Three short questions. Nothing is saved, take your time.
A PWM signal repeats every 20 ms and is on for 1.5 ms each time. What is its duty cycle?
- 1.5 %
- 7.5 %
- 75 %
Where should the servo get its power?
- From the board's 3V3 pin, it is the closest
- From a separate supply that suits the servo, with its ground joined to the board's GND
- From the signal pin itself
Show the answer
From a separate supply that suits the servo, with its ground joined to the board's GND. A servo draws quite a lot of power, especially when it starts, and the sudden demand can drop the board's voltage and make it reset [4]. So it gets its own supply [4]. The grounds are joined so that the signal and the supply share the same zero.
In ledcAttach(18, 50, 14), what does 50 mean?
- 50 degrees
- 50 pulses per second, one every 20 ms
- 50 % duty cycle
In short
- PWM switches a pin on and off over and over. The frequency is how many cycles per second, and the duty cycle is the share of each cycle spent on [1].
- A servo reads the length of the pulse, sent about every 20 ms: about 1 ms for one end, 1.5 ms for the middle, 2 ms for the other end. The exact ends vary [2][3].
- On the ESP32,
ledcAttach()sets the frequency and resolution, andledcWrite()sets the duty [5]. - A servo draws a lot of power when it starts. Give it its own supply, join the grounds, and never power it from the board’s
3V3pin [4].
Next step: C1, capacitors, to learn why a big capacitor calms a shaky supply.
Sources
Show the 5 sources
- Arduino, “Basics of PWM (Pulse Width Modulation)” (PWM is a way to get analog-like results with digital means by switching a signal on and off; the on time is the pulse width; the period is the inverse of the PWM frequency; Arduino’s PWM at about 500 Hz gives 2 ms periods; analogWrite scale 0 to 255, 255 is 100 % duty cycle, 127 about 50 %) — https://docs.arduino.cc/learn/microcontrollers/analog-output/
- Adafruit, “Arduino Lesson 14. Servo Motors”, “Servo Motors” (the servo expects a pulse roughly every 20 ms; 1 ms gives angle zero, 1.5 ms the centre, 2 ms 180 degrees; end points vary and many servos turn only about 170 degrees; continuous servos can rotate fully) — https://learn.adafruit.com/adafruit-arduino-lesson-14-servo-motors/servo-motors
- Adafruit, “Micro servo - TowerPro SG92R” (product ID 169) (rotates about 180 degrees; works without building a motor controller with feedback and gearbox; 1.5 ms is the middle, about 2 ms and about 1 ms the ends; default 1 ms to 2 ms may not give the full 180 degrees, try 0.75 ms to 2.25 ms; going too far could break the servo; voltage 4.8 V nominal, 3 V to 6 V) — https://www.adafruit.com/product/169
- Adafruit, “Arduino Lesson 14. Servo Motors”, “If the Servo Misbehaves” (a servo draws quite a lot of power, especially at start-up, and the sudden demand can drop the board’s voltage so that it resets; a capacitor of 470 uF or greater between GND and 5 V helps) — https://learn.adafruit.com/adafruit-arduino-lesson-14-servo-motors/if-the-servo-misbehaves
- Espressif, Arduino-ESP32 documentation, “LED Control (LEDC)” (the LEDC peripheral is primarily designed to control the intensity of LEDs and can also generate PWM signals for other purposes; ledcAttach(pin, freq, resolution) with resolution 1-14 bits, 1-20 bits for ESP32; ledcWrite(pin, duty) sets the duty) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/ledc.html