Home / Learn / Electronics basics

PWM explained: dimming LEDs, controlling motors and driving servos

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

Three PWM waveforms at 25, 50 and 75 percent duty cycle on a 5 volt pin, with the average voltage of each and an LED glowing brighter as the duty cycle rises
Beginner

A microcontroller pin is either on or off. Yet you can dim an LED smoothly and run a motor at half speed from the same pin. The trick is pulse width modulation, or PWM: switching the pin on and off so fast that the load responds to the average.

Duty cycle and frequency

A PWM signal has two settings:

  • Frequency: how many on-off cycles happen each second. 1 kHz means a cycle every 1 ms.
  • Duty cycle: the percentage of each cycle the pin is on. 0% is always off, 100% is always on.

The average voltage is the high voltage × the duty cycle. A 5 V pin at 25% duty averages 5 × 0.25 = 1.25 V. The pin isn't producing 1.25 V at any moment, though. It's at 5 V a quarter of the time and 0 V the rest, and that matters for some loads.

Why PWM works on LEDs and motors

An LED switches on and off almost instantly, so it really is flashing. Your eye averages the flashes, and above a few hundred hertz most people see a steady, dimmer light. A motor has inertia and its winding has inductance, so the current and speed smooth out between pulses. A heater responds even more slowly. In each case, the load does the averaging for you.

PWM is efficient because the switching transistor is either fully on (little voltage across it) or fully off (no current through it), so it wastes little power compared with dropping the voltage across a resistor.

PWM on an Arduino Uno

analogWrite(pin, value) takes a value from 0 (always off) to 255 (always on). On the Uno it works on pins 3, 5, 6, 9, 10 and 11, marked with a ~ on the board. Arduino's reference gives the frequency as about 490 Hz on most of those pins and about 980 Hz on pins 5 and 6.

const int LED_PIN = 9;   // a PWM pin (~)

void setup() {
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  for (int v = 0; v <= 255; v++) {   // fade up
    analogWrite(LED_PIN, v);
    delay(4);
  }
  for (int v = 255; v >= 0; v--) {   // fade down
    analogWrite(LED_PIN, v);
    delay(4);
  }
}

Despite the name, analogWrite() doesn't produce a true analogue voltage on the Uno. It produces PWM. (The Uno R4 does have a real DAC on pin A0, which is a different thing.)

PWM in MicroPython on a Raspberry Pi Pico

On the Pico, almost any GPIO can do PWM. You set the frequency yourself and the duty as a 16-bit number from 0 to 65535:

from machine import Pin, PWM
import time

led = PWM(Pin(15))
led.freq(1000)               # 1 kHz

while True:
    for d in range(0, 65536, 512):
        led.duty_u16(d)      # 0 = off, 65535 = fully on
        time.sleep_ms(5)

25% duty is duty_u16(16384). The Pico's outputs are 3.3 V, so the average at 25% is about 0.8 V.

Servos use PWM differently

Hobby servos read the width of each pulse, not the average. The usual standard is a pulse every 20 ms (50 Hz), with a width of about 1 ms for one end of travel, about 1.5 ms for the centre and about 2 ms for the other end. Many servos accept a wider range, so check the datasheet before pushing past 1 to 2 ms, or the servo will grind against its end stops. On an Arduino, the built-in Servo library generates the right pulses for you.

Driving bigger loads with PWM

A pin can only supply a few milliamps, so motors, LED strips and heaters need a transistor or MOSFET between the pin and the load. See transistors as switches and motors for makers. Fit a flyback diode across any motor or other inductive load.

Choosing a frequency

  • LEDs: a few hundred hertz upwards avoids visible flicker. Some people notice flicker or stroboscopic effects at low frequencies, especially in peripheral vision or with moving objects, so higher is kinder.
  • DC motors: low frequencies give an audible whine. Many motor drivers run at about 20 kHz, just above human hearing, but check your driver's maximum.
  • Servos: 50 Hz, as above.
Intermediate and advanced

Going deeper

Resolution versus frequency

A hardware PWM timer counts clock ticks. If the timer counts to N each cycle, the duty can be set in N steps and the frequency is the timer clock ÷ N. Doubling the frequency halves the number of steps available. On the RP2040, the PWM counter is 16 bits and is clocked from the 125 MHz system clock (through an optional divider), so at 1 kHz there are plenty of steps, but at 1 MHz there are only 125. MicroPython's duty_u16() scales your 0 to 65535 value onto whatever real resolution is available.

Turning PWM into a real analogue voltage

A resistor-capacitor low-pass filter averages PWM into a DC voltage with some ripple. Choose a corner frequency well below the PWM frequency: the ripple falls by roughly the ratio of the two for a single RC stage. For 980 Hz PWM, 10 kΩ and 10 µF give a corner of about 1.6 Hz, so the ripple is small, but the time constant is 0.1 s and the output takes a few tenths of a second to settle after a change. That trade-off between ripple and response time is why a DAC is better when you need a fast, clean analogue output. Try the numbers in the filter calculator.

Gamma: why fades look uneven

Perceived brightness isn't proportional to duty cycle: the eye is far more sensitive to changes at the dim end. A linear fade from 0 to 255 seems to jump up quickly and then crawl. Mapping the step through a curve such as duty = 255 × (step ÷ 255)2.2 gives a fade that looks even.

Motor drivers and current

With an inductive load, current keeps flowing during the off-time through the flyback diode or the driver's other transistor. At a high enough PWM frequency the motor current is almost steady, at roughly the duty × the stall current at the same speed, which is why PWM gives smooth torque at low speed.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.