Français

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:

  1. learn PWM, the on-off trick that carries that message,
  2. see how pulse length becomes angle,
  3. move a servo with a button, with a safe power supply.
The length of the pulse sets the angle Three drawings of the same hobby servo, its shaft towards you, with the horn, the little arm, at three angles: pointing left at angle zero, straight up at the middle, about 90 degrees, and pointing right at about 180 degrees. Under each, one 20 ms frame of the signal: a pulse at the start, then low until the next frame. Left, a 1 ms pulse; middle, 1.5 ms; right, 2 ms. A pulse comes about every 20 ms. Which side is zero, and the exact ends, vary from one servo to another. FIG. 1 — PULSE LENGTH TO ANGLEaangle zero (one end)1 ms020 msone 20 ms framebthe middle (about 90°)1.5 ms020 msone 20 ms framecabout 180° (other end)2 ms020 msone 20 ms frameA guide, not a law: which side is zero, and the exact ends, vary from one servo to another.
Tap the diagram to open it full screen.

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.

Pulse width to angle (interactive)
Pulse width to angle (interactive) Interactive simulation, not the real servo. Top, a servo seen with its shaft towards you, a travel arc marked 0, 90 and 180 degrees, and its horn. Bottom, one 20 ms period of the signal with its pulse. Move the slider from 0.5 to 2.5 ms; the usual range, 1.0 to 2.0 ms, is highlighted. The pulse, the duty-cycle bar and the horn move together: 1.0 ms is angle zero, 1.5 ms the middle, about 90 degrees, 2.0 ms about 180 degrees. Outside the usual range the horn stays at its end and a warning says the end of travel varies from one servo to another. simulation, not the servo0°90°180°01020 msshaded: 1 to 2 ms

Simulation of a typical servo, not your servo.

pulse 1.5 ms, duty 7.5 %, angle about 90°

duty 7.5 %

ledcWrite(18, 1228);

Inside the usual range: 1.0 to 2.0 ms.

This is the starting state: the controls need JavaScript.

Same period, different pulse widths Three PWM signals with the same period, drawn over three periods each. Top, on 25 % of each period; middle, 50 %; bottom, 75 %. Arrows mark one period and one pulse width on each. The period does not change, only the pulse width does. Below, the servo case: a 20 ms period with a thin 1.5 ms pulse, a duty cycle of 7.5 %. A servo measures that pulse; it does not average it. FIG. 2 — DUTY CYCLEaDuty cycle: the share of each period that is on25 %periodpulse width50 %75 %The period stays the same: only the pulse width changes.bThe servo case1.5 msperiod 20 ms7.5 %= 1.5 / 20the servo measures this pulse, it does not average
Tap the diagram to open it full screen.

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 3V3 pin, 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 GND pin 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.

A2 wiring: servo signal on 18, its own 4.8 V pack, common GND Two panels. a, breadboard view. The DevKitC sits off the breadboard, USB on the left, powered by its USB cable; GPIO 18 is on its bottom header, so female jumpers go straight on its pins. On the breadboard, the bottom rails are the servo supply, 4.8 V; the top rails are not used. A pack of 4 NiMH AA cells, switched off while you wire: 1 red, pack plus to the bottom plus rail; 2 black, pack minus to the bottom minus rail. The servo's plug, brown minus, red plus, orange signal: 3 red, servo plus to the plus rail; 4 black, servo minus to the minus rail; 5 yellow, servo signal to GPIO 18. 6 black, a thick wire labelled common GND, from the minus rail to a GND pin of the DevKitC. A 470 microfarad electrolytic capacitor straddles the two bottom rails next to the servo plug, stripe on the minus rail, rated 10 V or more. The button straddles the gap in rows 10 and 12: 7 blue, GPIO 27 to row 10; 8 black, its opposite leg, row 12, to the minus rail. A dashed red line from the 3V3 pin, crossed out: never power the servo from 3V3. The servo's plus goes to its own pack only, never to a pin of the board. b, schematic: the ESP32's GPIO 18 drives the servo's signal input. The battery and the polarised capacitor are in parallel across the servo's plus and minus. A bold line joins the battery's minus, the servo's minus and the ESP32's GND: common GND. The button sits between GPIO 27 and that GND line. A crossed-out dashed line from 3V3 to the servo's plus. FIG. 3 — WIRING, SERVO ON ITS OWN SUPPLYaBreadboard viewENBOOT5VCLKCMDD0D3D1D215132GND0124141627172652518331932GND352134RXVNTXVP22EN233V3GND+−−+jihgfedcba1510121518top rails: not usedcommon GNDservoplug: brown −, red +, orange signal−++++ONOFF4 × NiMH AA, 4.8 Vswitched off while you wire470 µF,stripe on −10 V or morebottom rails:servo supplybutton3V3 → servo: neverGND2718GNDGNDUSB cable:powers theboard123456781red: pack + → bottom + rail2black: pack − → bottom − rail3red: servo red (+) → + rail4black: servo brown (−) → − rail5yellow: servo orange (signal) → GPIO 186black: − rail → GND pin: common GND7blue: GPIO 27 → button (row 10)8black: button, opposite leg → − railThe servo's + goes to its own pack only, never to a pin of the board. The + rail feeds only the servo and the capacitor.GPIO 18 is on the bottom header: the board sits off the breadboard, female jumpers go on its pins.bSchematicESP32DevKitC3V31827GNDMservoS+−signal: pulses only++4 × NiMH4.8 V470 µF10 V or morecommon GNDbuttonnever: 3V3 is not the servo's supply
Tap the diagram to open it full screen.

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 µs is the whole conversion. For 1500 µs that gives 1228 steps (the sketch drops the decimals) in a 16,384-step period: 7.5 %.
  • angleToPulseUs() uses map() to go from angle to pulse. Then setServoPulseUs() converts the pulse to duty.
  • The button works by edge: the servo moves once per press, not once per loop. The wasPressed variable remembers the last reading.
14 bits: the 20 ms period cut into 16,384 steps A long bar stands for one 20 ms period, cut into 16,384 thin slices, too thin to draw one by one. The first 1,228 slices are coloured: that is the 1.5 ms pulse, 7.5 % of the bar. A zoomed inset around the end of the pulse shows single slices: each lasts about 1.2 microseconds; slice 1,228 is the last one on, slice 1,229 the first one off. The conversion: duty = 1500 µs × 16,384 / 20,000 µs = 1,228.8, and the sketch drops the decimals: 1,228. FIG. 4 — DUTY IN STEPS020 ms16,384 steps = 20 ms1,228 steps on ≈ 1.5 ms (7.5 %)slices not to scale1,228: last on1,229: first off1 step ≈ 1.2 µszoomduty = 1500 µs × 16,384 / 20,000 µs = 1,228.8the sketch drops the decimals: ledcWrite(18, 1228)
Tap the diagram to open it full screen.

Try your own changes

Change one thing, upload, observe.

  1. Other positions. Edit the positions list: try {0, 45, 90, 135, 180}. Make sure positionIndex wraps around: it uses % POSITION_COUNT.
  2. Find the ends of your servo. Change MIN_US to 900, then 800, and MAX_US to 2100, then 2200, one step at a time. Stop as soon as the servo strains or buzzes at the end of its travel [3].
  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)?
  4. Read the duty. Print duty in setServoPulseUs(). 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 GND pin 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_US and MAX_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.

  1. 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 %
    Show the answer

    7.5 %. Duty cycle is the share of each period that the signal is on [1]. 1.5 ms out of 20 ms is 1.5 / 20 = 0.075, which is 7.5 %. For a typical servo, a pulse near 1.5 ms means the middle position [2][3].

  2. 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.

  3. In ledcAttach(18, 50, 14), what does 50 mean?

    • 50 degrees
    • 50 pulses per second, one every 20 ms
    • 50 % duty cycle
    Show the answer

    50 pulses per second, one every 20 ms. The second number is the PWM frequency [5]. 50 per second means one pulse every 1 / 50 = 0.02 s, which is 20 ms, the rhythm a servo expects [2]. The 14 is the resolution in bits [5].


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, and ledcWrite() 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 3V3 pin [4].

Next step: C1, capacitors, to learn why a big capacitor calms a shaky supply.


Sources

Show the 5 sources
  1. 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/
  2. 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
  3. 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
  4. 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
  5. 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

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.