13.16 Hobby servos
The car steers with a hobby servo, a DS3218, that turns the steering linkage through a horn on its output shaft. A servo is a complete position controller in one housing: we send it a pulse that says where the shaft should be, and its own electronics drive the shaft there and hold it.
The DS3218 is sold under many names, often by its stall torque in kilograms at one centimetre from the shaft, with a set of horns and screws (Figure 13.16.1).
The project folders code/servo_center and code/servo lie next to this chapter and are built as the PlatformIO chapter describes.
The Guide
Step 1: Wire the servo
The servo takes its power from the 7.0 V rail of the XL4015 buck converter, the rail that also feeds the ESP32 through VIN; only the signal wire goes to a GPIO pin (Figure 13.16.2).
VIN). The 470 µF capacitor lies across the rail at the servo. GPIO 13 drives the signal wire, and every ground is joined. The optional 10 kΩ pot lies between 3V3 and ground with its wiper on GPIO 35.
Make the connections with the battery disconnected:
| From | To |
|---|---|
Buck OUT+ (7.0 V) |
Servo red wire, ESP32 VIN, capacitor + |
Buck OUT− |
Servo brown wire, ESP32 GND, capacitor − (stripe) |
ESP32 GPIO13 |
Servo orange wire (signal) |
ESP32 3V3, GND, GPIO35 |
10 kΩ potentiometer: outer pins, outer pin, middle pin |
The rail is the one set up in Buck converters, with the 470 µF capacitor placed at the servo as in its Step 3. Measure 7.0 V on the rail before the servo is connected: a converter at its factory setting can put up to 12.6 V on the servo and the ESP32 and destroy both. Check the wire colours against the table before applying power. The potentiometer is optional; one command of Step 3 lets it turn the servo.
The servos in our kits are labelled DC 4.8-7.4 V, made to run from a 2S LiPo at its nominal 7.4 V (2 × 3.7 V), and the 7.0 V rail lies inside that range. A fully charged 2S pack gives 8.4 V, above the label, another reason to feed the servo from the buck converter. Versions of the DS3218 are also sold labelled 4.8-6.8 V; set the rail no higher than the maximum printed on yours.
The ESP32 now runs from VIN, but calibration also needs the USB cable for the serial monitor, so for a while the board has two supplies. Before connecting both, make the check of USB and VIN at the same time: on a board without the diode, the rail drives current into the computer’s USB port.
Once the servo is wired, flash the servo program from Chrome or Edge, without PlatformIO, and type the commands of Step 3 in the page’s serial monitor. If the horn follows them, the wiring is right, and a fault in our own build lies in the code.
Step 2: Center the servo
Create a PlatformIO project called servo_center and replace its platformio.ini with the plain file of the PlatformIO chapter:
[env:esp32dev]
platform = espressif32@8.0.0
board = esp32dev
framework = arduino
upload_speed = 921600
monitor_speed = 115200The first program sends one pulse width, 1500 µs, the middle of the servo’s travel. Replace src/main.cpp with:
#include <Arduino.h>
const int servoPin = 13;
const int servoFreqHz = 50; // one pulse every 20 ms
const int servoBits = 16; // the 20 ms are counted in 2^16 = 65536 steps
// A pulse of us microseconds lasts us/20000 of the 65536 steps.
int usToDuty(int us) {
return us * 65536 / 20000;
}
void setup() {
Serial.begin(115200);
ledcAttach(servoPin, servoFreqHz, servoBits);
// Center the servo
ledcWrite(servoPin, usToDuty(1500));
Serial.println("Servo centered at 1500 us");
}
void loop() {
}ledcAttach connects GPIO 13 to the ESP32’s PWM hardware, which from then on sends a pulse every 20 ms, and ledcWrite sets how long each pulse is. loop() stays empty because the hardware repeats the pulse until the board is switched off. Generating the pulse with LEDC explains the numbers.
Build and upload with the BOOT button as before; the servo turns to its middle position and stays there. Unscrew the horn from the shaft, or unhook the steering link from it, and refit the horn so that the linkage holds the wheels as close to straight as the spline allows. The DS3218 output shaft has 25 teeth, so the horn moves in steps of \(360°/25 = 14.4°\). Hook up the linkage again.
Step 3: Command the servo from the serial monitor
The second program takes pulse widths typed in the serial monitor. Create a project called servo with the same platformio.ini, and put the part that drives the servo in its own file, src/servo.h:
// servo.h: the steering servo. The car program includes this file unchanged.
#pragma once
#include <Arduino.h>
const int servoPin = 13;
const int servoFreqHz = 50; // one pulse every 20 ms
const int servoBits = 16; // the 20 ms are counted in 2^16 = 65536 steps
int currentUs = 1500; // the pulse width sent last
// A pulse of us microseconds lasts us/20000 of the 65536 steps.
int usToDuty(int us) {
return us * 65536 / 20000;
}
void applyUs(int us) {
us = constrain(us, 400, 2600); // no hobby servo needs more, and no command can send more
currentUs = us;
ledcWrite(servoPin, usToDuty(us));
}
void servoBegin() {
ledcAttach(servoPin, servoFreqHz, servoBits);
applyUs(1500);
}applyUs is the one function that moves the servo: it sends a pulse width in microseconds and remembers it in currentUs.
src/main.cpp reads the commands and runs the modes that move the servo by themselves:
#include <Arduino.h>
#include "servo.h"
// Serial commands (end with Enter):
// u <us> set pulse width in microseconds, e.g. u 1500
// sweep auto-sweep 500..2500 us and back
// scan slow scan 400..2600 us in 50 us steps
// pot follow the potentiometer on GPIO 35
// stop hold current position
// ? print current state
// h show help
const int potPin = 35; // the wiper of the pot, as in the analog chapter
const int minUs = 500; // the hobby standard: 500 us is one end of the travel,
const int maxUs = 2500; // 2500 us the other, 1500 us the middle
enum Mode { HOLD, SWEEP, SCAN, POT };
Mode mode = HOLD;
const char* modeName[] = {"hold", "sweep", "scan", "pot"};
int sweepDir = 1; // sweep: 1 towards 2500 us, -1 towards 500 us
unsigned long lastStepMs = 0;
String line = ""; // the characters received since the last Enter
void displayHelp() {
Serial.println("Commands: u <us> | sweep | scan | pot | stop | ? | h");
}
void printState() {
Serial.printf("current=%d us mode=%s\n", currentUs, modeName[mode]);
}
void handleLine(String s) {
s.trim();
if (s.length() == 0) return;
if (s == "h") { displayHelp(); return; }
if (s == "?") { printState(); return; }
if (s == "stop") { mode = HOLD; Serial.println("stopped"); return; }
if (s == "sweep") { mode = SWEEP; Serial.println("sweeping"); return; }
if (s == "scan") { mode = SCAN; Serial.println("scanning"); return; }
if (s == "pot") { mode = POT; Serial.println("following pot"); return; }
int sp = s.indexOf(' ');
if (sp < 0) { Serial.println("unknown command"); return; }
String cmd = s.substring(0, sp);
int val = s.substring(sp + 1).toInt();
if (cmd == "u") { mode = HOLD; applyUs(val); }
else { Serial.println("unknown command"); return; }
printState();
}
void setup() {
Serial.begin(115200);
servoBegin();
displayHelp();
printState();
}
void loop() {
// Collect characters until Enter, then handle the line
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') { handleLine(line); line = ""; }
else if (line.length() < 64) { line += c; }
}
// Sweep, scan and pot move the servo one step at a time
if (mode == SWEEP && millis() - lastStepMs >= 20) {
lastStepMs = millis();
int us = currentUs + sweepDir * 10;
if (us >= maxUs) { us = maxUs; sweepDir = -1; }
if (us <= minUs) { us = minUs; sweepDir = 1; }
applyUs(us);
}
if (mode == SCAN && millis() - lastStepMs >= 500) {
lastStepMs = millis();
int us = currentUs + 50;
if (us > 2600) us = 400;
applyUs(us);
Serial.printf("%d us\n", us);
}
if (mode == POT && millis() - lastStepMs >= 100) {
lastStepMs = millis();
int raw = analogRead(potPin); // 0 to 4095
int us = map(raw, 0, 4095, minUs, maxUs);
applyUs(us);
Serial.printf("raw=%d us=%d\n", raw, us);
}
}The line reader and handleLine are those of Serial communication, with u 1500 in place of blink 200. In the three moving modes loop() also takes one step whenever enough time has passed since the last, timed with millis() as in Waiting without delay(), so stop takes effect at once. sweep moves 10 µs every 20 ms between 500 and 2500 µs. scan moves 50 µs every half second from 400 to 2600 µs and prints each value. pot reads the potentiometer ten times per second and maps its 0 to 4095 onto 500 to 2500 µs with map() from Reading an analog signal. Figure 13.16.3 shows the pulse width each mode sends.
Build, upload and open the serial monitor. The servo moves to 1500 µs at start-up, and the monitor shows:
Commands: u <us> | sweep | scan | pot | stop | ? | h
current=1500 us mode=hold
Try the commands with the horn off the shaft, or the linkage unhooked. u 500, u 1500 and u 2500 turn the shaft to one end, the middle and the other end of its travel. scan finds the ends of the servo’s range: below one pulse width and above another the shaft no longer moves. sweep and pot show how fast the servo turns and how smoothly it follows.
Hobby servos share one standard: a pulse every 20 ms, 1500 µs for the middle of the travel and 500 to 2500 µs for the two ends. Any pulse width in that window is safe for the servo on its own, so a program that sends 500 to 2500 µs drives every servo in the kit. The mechanism the servo turns is another matter: a steering linkage reaches its stops long before the servo reaches the ends of its travel, and straight ahead is rarely exactly 1500 µs. Calibration, in Calibrating the steering, finds the three pulse widths of this servo in this car: full left, straight ahead and full right.
How It Works
The pulse signal
A hobby servo reads one number from its signal wire: the duration of a pulse. The receiver or microcontroller sends a pulse every 20 ms, a frame rate of 50 Hz, and the width of the pulse sets the commanded angle (Figure 13.16.4). The voltage level carries no information, so the signal survives a long wire, a sagging supply and electrical noise far better than a voltage would.
On the oscilloscope the signal from the ESP32 looks like Figure 13.16.5. The scope measures the period, 20.10 ms, and the width of the pulse, 2.500 ms, and reports their ratio as the duty cycle, \(2.500/20.10 = 12.4~\%\). The pulse rises by about 3.3 V, the logic level of the ESP32, at 2 V per division.
The DS3218 maps 500 to 2500 µs onto 180°, so the angle changes by
\[ \frac{180°}{2500\ \mu\text{s} - 500\ \mu\text{s}} = 0.09\ °/\mu\text{s}, \]
i.e. 11.1 µs per degree, with center at 1500 µs. Older servos use 1000 to 2000 µs for their full travel, and many libraries still default to that window. The 50 Hz frame comes from analog radio systems; it works with every servo and is fast enough for steering.
Inside the servo
The housing holds a small brushed DC motor, a gearbox and a control board. The gearbox reduces the motor speed many times over and multiplies its torque by the same factor. A potentiometer turned by the output shaft gives a voltage proportional to the shaft angle. The control board measures the width of each incoming pulse, converts it to an angle and compares that with the potentiometer. The difference is the error, and the board drives the motor to reduce it, harder the larger it is: a proportional feedback controller inside the servo (Figure 13.16.6).
The servo therefore holds its position: when the steering pushes back on the horn, the shaft moves a little, an error appears and the motor pushes back. If the commanded angle lies beyond a mechanical stop, the error never vanishes and the motor pushes at full current indefinitely; the calibration avoids this binding.
The controller ignores errors smaller than its deadband, about 3 µs for the DS3218. A 3 µs change in pulse width is \(3 \times 0.09° \approx 0.27°\) at the shaft. Without a deadband the motor would twitch around every target, chasing the noise in the potentiometer reading. With it, the servo stands still within a quarter of a degree, and the pulse we send needs a resolution of about 1 µs or better to use all the precision the servo has.
The DS3218 data are:
| Quantity | Value |
|---|---|
| Supply voltage (label) | 4.8 to 7.4 V on our servos (4.8 to 6.8 V on some versions) |
| Stall torque | about 19 kg·cm (1.9 N·m) at 5 V, 21.5 kg·cm (2.1 N·m) at 6.8 V |
| Speed (no load) | about 0.16 s per 60° at 5 V, 0.14 s at 6.8 V |
| Pulse range | 500 to 2500 µs over 180°, center 1500 µs |
| Deadband | 3 µs |
| Stall current | about 1.8 A at 5 V, 2.6 A at 6.8 V |
The voltage range is printed on the servo. The other values come from reseller listings and a servo database, which mostly agree; DSSERVO publishes no datasheet we could retrieve, so treat torque and current as approximate. A 270° version of the DS3218 spreads the same pulse range over 270°.
Stall current and the supply
A motor at standstill has no back-EMF, so its current is limited only by the resistance of its winding. The servo draws this stall current every time it starts a large move and whenever it pushes against a load it cannot move, such as a binding linkage. For the DS3218 that is around 2.6 A at 6.8 V, against a few milliamperes at rest.
A computer’s USB port delivers 0.5 to 0.9 A, too little for the servo. The ESP32 itself needs some 100 to 250 mA with WiFi active, and its 3.3 V regulator needs about 4.5 V at VIN. When the servo pulls the 5 V of a USB port down, the chip’s 3.3 V supply sags with it and its brown-out detector resets it. The serial monitor shows Brownout detector was triggered followed by the start-up text: the board restarts every time the servo moves. The XL4015 module, sold for up to 5 A, supplies the stall current with room to spare, so servo and ESP32 share its rail.
The capacitor covers the microseconds before the converter follows a current step; it cannot carry a stall that lasts milliseconds, as When the input sags: dropout computes. Placed close to the servo, it also keeps the current spikes out of the wires the ESP32 shares.
Frequency, duty cycle and resolution
The servo signal is one case of pulse-width modulation, PWM: a pin switches between high and low in a fixed rhythm, and the information lies in how long each pulse lasts. The rhythm is the period \(T\), the time from the start of one pulse to the start of the next, and the number of periods per second is the frequency,
\[ \boxed{f = \frac{1}{T}} \tag{13.16.1}\]
For the servo \(T = 20\) ms, so \(f = 1/0.020~\text{s} = 50\) Hz. The fraction of the period that the pin is high is the duty cycle,
\[ \boxed{D = \frac{t_p}{T}} \tag{13.16.2}\]
where \(t_p\) is the pulse width. The servo’s middle, 1500 µs, is \(D = 1500/20\,000 = 7.5\) %, and the hobby range of 500 to 2500 µs spans only \(D = 2.5\) to \(12.5\) %. The pin is low for most of every period.
A microcontroller counts each period off in \(2^b\) equal steps, where \(b\) is the resolution in bits, and the pulse can only end at the end of a step. The frequency says how often the pattern repeats, the resolution how finely each period is divided, and the smallest change of pulse width is one step, \(T/2^b\).
Figure 13.16.7 shows the three settings on a slow signal. Choose 3 bits and drag the duty cycle: it jumps in steps of \(1/8 = 12.5\) %, and the pulse ends on one of the eight ticks of each period. Raise the frequency: periods and steps shorten together, and the duty cycle stays where it was. Then choose 8 bits, and the duty cycle moves almost smoothly.
Generating the pulse with LEDC
The ESP32’s PWM peripheral, LEDC (named for dimming LEDs), produces pulse trains in hardware: the program sets the pulse width and the peripheral repeats the pulse. LEDC has 16 channels. A channel counts from 0 up to \(2^b - 1\) once per period and keeps its output high while the count is below the duty count, the duty cycle in steps, \(D \cdot 2^b\). ledcAttach(servoPin, 50, 16) takes a free channel, makes it count to 65 535 fifty times a second and routes it to GPIO 13; ledcWrite(servoPin, duty) then sets the duty count (Figure 13.16.8).
At 50 Hz and 16 bits one count lasts
\[ \frac{T}{2^{16}} = \frac{20\,000\ \mu\text{s}}{65\,536} = 0.305\ \mu\text{s}, \]
and with 13.16.2 a pulse of width \(t_p\) needs the duty count
\[ \text{duty} = D \cdot 2^{16} = \frac{t_p \cdot 2^{16}}{T} = \frac{t_p \cdot 2^{16} \cdot f}{10^6}, \]
with \(t_p\) and \(T\) in microseconds and \(f\) in hertz. With \(T = 20\,000\ \mu\text{s}\) this is the line in usToDuty:
int usToDuty(int us) {
return us * 65536 / 20000;
}For center, \(1500 \times 65\,536 / 20\,000 = 4915.2\). Integer division drops the fraction and gives 4915, and the pulse produced is \(4915 \times 0.305 = 1499.9\ \mu\text{s}\). The ends of the DS3218’s range give 1638 at 500 µs and 8192 at 2500 µs.
Multiplying first keeps the fraction until the division; us / 20000 * 65536 would give 0 for every pulse shorter than 20 ms. The product must then fit in an int, whose largest value on the ESP32 is \(2^{31} - 1 = 2.15 \times 10^9\). For 2600 µs, the longest pulse applyUs lets through, it is \(2600 \times 65\,536 = 1.7 \times 10^8\), well inside. A typed u 40000 would give \(2.6 \times 10^9\), which silently wraps around to a negative number; applyUs clamps the pulse width before it computes the duty partly for this reason.
The servo resolves about 3 µs, and a count of 0.305 µs is ten times finer, so at 16 bits the PWM step never limits the steering. With 10 bits a count would be \(20\,000/1024 = 19.5\ \mu\text{s}\), i.e. \(1.8°\) per step, coarse enough to see on the wheels (Figure 13.16.8, bottom). More bits bring nothing the servo can use, and 16 bits is well within what LEDC can do at 50 Hz.
The 16 channels share eight timers, and channels on one timer have the same frequency and resolution. ledcAttach gives a channel the timer of another channel with the same settings, or a free timer, so the servo at 50 Hz gets a timer of its own. A newly attached channel starts with duty 0, so GPIO 13 stays low until servoBegin writes the first pulse, the center pulse.
Examples written for version 2 of the Arduino core use ledcSetup and ledcAttachPin, which no longer build (platformio.ini line by line).
The ESP32Servo library
Most ESP32 servo examples use the library madhephaestus/ESP32Servo, added in platformio.ini as
lib_deps =
madhephaestus/ESP32Servo@^3.0.0It provides the Servo class known from Arduino boards: Servo steering; declares a servo, steering.attach(servoPin, 500, 2500) sets it up with its pulse limits, and steering.writeMicroseconds(1500) or steering.write(90) positions it. Underneath, the library uses the same LEDC peripheral and computes the same duty, but two differences matter for the car. It picks the LEDC channel from its own record of the channels it has handed out and knows nothing of those ledcAttach gave the motor. If the motor is set up first, the library can choose the motor’s channel, and the servo then receives the motor’s 20 kHz signal. And version 3.2.1, which ^3.0.0 resolves to at the time of writing, uses 10 bits by default, the 19.5 µs steps computed above, unless steering.setTimerWidth(16) is called before attach.
Since the car combines a servo with a motor driver, we write the servo with ledcAttach ourselves: every channel and timer then has one allocator, and servo.h is short enough to read in full. The library suits a project with several servos and no other PWM.
Calibrating the steering
Steering geometry limits how far the wheels can turn. When the servo asks for more, the linkage binds: the wheel knuckle is against its stop, and for as long as the command stays the servo pushes with full force, draws its stall current, heats up and strains the printed parts. We therefore look for the pulse widths that turn the wheels fully without touching the stops, and give the car a steering command that never asks for more.
Find the end points
Put the car on a stand, wheels off the ground, with the horn fitted and the linkage hooked up as in Step 2, and run the program of Step 3:
- Send
u 1500and trim the center in steps of 10 µs (about 1°),u 1510,u 1520oru 1490, until the wheels point straight ahead. This pulse width iscenterUs. - Step toward one side in 20 µs steps. Stop at the first step where the wheel reaches its stop: the servo starts to hum, the linkage flexes visibly, or the current on a bench supply jumps. Go back 30 µs from there. If the wheels turned left, this pulse width is
leftUs, otherwiserightUs. - Send the center value again and repeat step 2 toward the other side.
- Send
uwith each value found, e.g.u 1220, and check that the servo is quiet at both ends.
The potentiometer makes step 2 quicker: send pot, turn the knob slowly until the wheel reaches its stop, read us in the monitor, and turn back until us has changed by 30 µs.
Which side needs the longer pulse depends on how the servo is mounted, so leftUs may be the larger number, and the two end points often lie at different distances from center.
A servo that hums while it stands still is stalled against a stop and draws its full stall current, more than 2 A for the DS3218. Send the center value at once. A few seconds of this make the motor and the buck converter hot; minutes can destroy the servo.
Steer between the end points
The three values go at the end of servo.h, with the function the car steers by:
// Steering end points in microseconds, from the calibration
const int leftUs = 1220;
const int centerUs = 1530;
const int rightUs = 1870;
// Steering from -100 (full left) through 0 (straight ahead) to +100 (full right)
void steer(int percent) {
percent = constrain(percent, -100, 100);
if (percent < 0) applyUs(map(percent, -100, 0, leftUs, centerUs));
else applyUs(map(percent, 0, 100, centerUs, rightUs));
}steer is two straight lines drawn by map(), one per side: −100 gives leftUs, 0 gives centerUs and +100 gives rightUs (Figure 13.16.9). Two lines keep 0 at the calibrated center even when the sides are unequal, and whatever the command, the pulse stays between the end points, so the car never pushes the linkage into its stops.
steer() with the calibration above: 310 µs to the left and 340 µs to the right of center, so the two sides have different slopes. Commands beyond ±100 are clamped.
To try it, add a command to handleLine in main.cpp, next to the line for u:
else if (cmd == "s") { mode = HOLD; steer(val); }and upload again. Now s -100 and s 100 turn the wheels fully left and right without humming, s 0 sets them straight, and s 50 and s -50 turn them half way. The project code/servo contains these additions.
If the servo is replaced, or the horn is moved a tooth on the spline, find the end points again.
Exercises
Exercise 1
Add a command a <deg> to main.cpp that turns the shaft to an angle from 0 to 180°. Use map() from Reading an analog signal to turn the angle into a pulse width between 500 and 2500 µs, and send it with applyUs. Check that a 0, a 90 and a 180 give the same positions as u 500, u 1500 and u 2500. Then write a second version that maps the angle straight to the duty count and calls ledcWrite itself, without usToDuty. Which two numbers take the place of 500 and 2500? Which version would you rather read a month later, and what does the second one lose that applyUs gave the first?
Exercise 2
Compute the LEDC duty for a pulse of 1250 µs at 50 Hz and 16 bits, and the pulse width the servo receives. A classmate writes usToDuty as us * (65536 / 20000). Which duty does that give for 1500 µs, which pulse width reaches the servo, and by how many degrees is the horn off? Rewrite usToDuty for a frame rate of 200 Hz. What is the longest pulse that fits in a 200 Hz frame?
Exercise 3
A student’s steering calibration gives leftUs = 1960, centerUs = 1480 and rightUs = 1100. Which pulse width does steer(50) send, and which does steer(-25) send? By how many degrees does the horn turn between full left and full right?
Exercise 4
The ESP32Servo library at its default 10 bits divides the 20 ms frame into 1024 counts. How many distinct pulse widths lie between 1220 and 1870 µs, and how many with 16 bits? Express the step size in degrees at the horn and compare it with the deadband.
Exercise 5
Open the Falstad circuit simulator and build a 7.0 V source with a 0.1 Ω series resistor (the wires and the converter’s output resistance) feeding a node with a 470 µF capacitor to ground. Add a 2.7 Ω resistor (a stalled servo at 7 V) through a switch from the node to ground, and a 1 kΩ load for the ESP32. Close the switch and read the node voltage on the scope. How far does it fall, and how much faster does it fall without the capacitor? What does the capacitor change, and what does it not change, once the switch has been closed for a few milliseconds?