LeepCast
Subscribe
All posts
Hardware

PWM Explained: Duty Cycle, Frequency, and Resolution for LEDs, Motors, and Servos

Pulse-width modulation lets a digital pin act like a dimmer, a motor throttle, or a crude DAC. Here is how timers generate it, why frequency and resolution trade against each other, and how to pick settings for each kind of load.

LeepCast6 min read

Most microcontroller pins can only be fully on or fully off, yet the same chips dim LEDs smoothly, control motor speed, and position servos. The trick behind all three is pulse-width modulation (PWM): switching a pin on and off fast enough that the load responds to the average rather than to each individual pulse. PWM looks simple, but choosing the wrong frequency or misunderstanding resolution is behind a lot of whining motors, jittery servos, and noisy analog outputs.

What a PWM signal actually is

A PWM signal is a rectangular wave with a fixed period. Two numbers describe it. The frequency is how many periods happen per second. The duty cycle is the fraction of each period during which the output is high. A 25% duty cycle means the pin is high for a quarter of every period and low for the rest.

For a load that averages the signal, the effective voltage is the duty cycle multiplied by the high voltage. On a 3.3 V pin, 25% duty averages to about 0.83 V and 50% averages to 1.65 V. Microchip's documentation puts it the same way: a 50% duty cycle corresponds to half the supply voltage and 75% to three quarters of it.

Arduino's analogWrite() is the most familiar example. Its value argument runs from 0 (always off) to 255 (always on), so analogWrite(9, 64) produces roughly 25% duty. Despite the name, the official reference notes that analogWrite has nothing to do with the analog input pins or analogRead; on most pins it simply emits PWM, and only a few boards with a real DAC pin produce a true analog voltage.

How a hardware timer generates PWM

PWM is almost never produced by toggling a pin in software. A hardware timer does it. The timer counts clock ticks from zero up to a top value, then wraps around; that wrap defines the period. A compare register holds a second number. While the counter is below the compare value the output is high, and once the counter passes it the output goes low. This is called edge-aligned PWM. Changing the compare value changes the duty cycle, and the hardware keeps generating the waveform with no CPU involvement.

Because several output pins are often driven by one timer, they also share its period. The MicroPython documentation warns that setting the frequency on one PWM object may affect other objects that share the same underlying generator. Pins on the same board do not always default to the same rate either: on an Arduino UNO R3 most PWM pins run at 490 Hz, while pins 5 and 6 run at 980 Hz.

The frequency versus resolution trade-off

Resolution is how many distinct duty-cycle steps are available, and it is set by how many clock ticks fit in one period. Texas Instruments states the relationship for an edge-aligned timer as 2^N = fCLOCK / fPWM, where N is the resolution in bits. Every time you halve the PWM frequency, you gain one bit of resolution.

  • 32 MHz timer clock: 125 kHz PWM gives 8 bits, 31.3 kHz gives 10 bits, 7.8 kHz gives 12 bits.
  • 16 MHz timer clock: 62.5 kHz gives 8 bits, 15.6 kHz gives 10 bits, 3.9 kHz gives 12 bits.
  • The same arithmetic shows why you cannot have both a very high frequency and very fine duty control from one clock.

Software APIs can hide this. MicroPython's duty_u16() always accepts a 16-bit number, but its documentation explains that at 300 kHz the hardware may only have 8 bits of real resolution, so the low 8 bits of the value are simply ignored. Frequency is also quantized: with an 80 MHz base clock, asking for 300 kHz needs a divider of 266.67, which rounds to 267 and yields about 299,625 Hz instead. Always check what the hardware actually produced rather than what you requested.

Choosing settings for each kind of load

LEDs

An LED responds almost instantly, so it really does switch on and off with every pulse; the smooth dimming you see comes from your eye averaging the light. Arduino's default PWM rates of a few hundred hertz to around a kilohertz are routinely used to dim indicator LEDs. The main design question is resolution: if 256 steps feel too coarse for a slow fade, the formula above says you need either a lower PWM frequency or a faster timer clock.

Brushed DC motors

A motor winding is an inductor, and its electrical time constant (inductance divided by resistance) decides how much the current ripples during each PWM period. When the period is much shorter than that time constant, the motor sees nearly steady current. Frequency choice is a balance: below about 1 kHz the winding tends to whine audibly and motion can be jerky at low duty, while very high frequencies increase switching losses in the driver transistor. A practical reference for embedded motor control suggests 20 kHz as a sensible default for small brushed motors under about 5 A, since it is above the range people can normally hear without letting switching losses dominate. The default Arduino rates of 490 Hz and 980 Hz fall squarely in the audible range, which is why motors driven straight from analogWrite often hum.

Hobby servos

Servos are the exception that confuses people: they do not respond to duty cycle as a ratio. They read the width of each pulse. The Arduino Servo library documentation describes the convention: a 1000 microsecond pulse is fully counter-clockwise, 2000 microseconds is fully clockwise, and 1500 is centred. Many servos accept a wider span, roughly 700 to 2300 microseconds, but driving one past its mechanical end stop puts it in a high-current state, often audible as a growl, which should be avoided. Because the pulse width is what matters, an API that sets width directly in time units is safer than computing a percentage.

Using PWM as a cheap DAC

Pass a PWM signal through a low-pass filter and you get a usable analog voltage. A single resistor and capacitor form a first-order filter with a cutoff frequency of 1 / (2πRC). TI's guidance is that the cutoff should sit at least an order of magnitude below the PWM frequency. Microchip adds the other half of the trade-off: the cutoff must still be high enough not to distort the signal you actually want, and a higher PWM frequency makes the ripple easier to remove.

As a worked example, take 10-bit PWM at 31.3 kHz. A cutoff no higher than about 3.1 kHz meets the one-decade rule. A 10 kΩ resistor with a 10 nF capacitor gives 1 / (2π × 10,000 × 0.00000001), roughly 1.59 kHz, which fits. If the filtered output feeds a low-impedance input, Microchip recommends a buffer amplifier between the filter and the load, because the load would otherwise drain the capacitor and bring the ripple back. When ripple must be lower still, a higher-order filter attenuates the PWM edges more steeply.

A worked example in MicroPython

The script below runs on a Raspberry Pi Pico with MicroPython. It steps an LED through several brightness levels using duty_u16, then sweeps a servo using duty_ns so the pulse width is expressed directly. On the RP2040, GPIO 15 and GPIO 16 belong to different PWM slices, so giving them different frequencies does not cause one setting to overwrite the other.

python
from machine import Pin, PWM
import time

# LED: 1 kHz carrier, brightness set as a 16-bit duty value (0..65535)
led = PWM(Pin(15), freq=1000, duty_u16=0)
for pct in (0, 25, 50, 75, 100):
    led.duty_u16(pct * 65535 // 100)
    time.sleep(0.5)

# Servo: 50 Hz frame (20 ms period), position set by pulse width
servo = PWM(Pin(16), freq=50, duty_ns=1_500_000)  # 1.5 ms = centre
for us in (1000, 1500, 2000, 1500):
    servo.duty_ns(us * 1000)  # microseconds -> nanoseconds
    time.sleep(1)

led.deinit()
servo.deinit()

The equivalent LED step on an Arduino UNO is a single call such as analogWrite(9, 64) for about 25% duty, with no pinMode() needed first, as the reference points out. Driving a servo there is better left to the Servo library's writeMicroseconds(), which handles the pulse timing for you.

A short PWM checklist

  1. Identify what the load responds to: average voltage (LEDs, motors, filtered DAC) or pulse width (servos).
  2. Compute resolution from 2^N = fCLOCK / fPWM before promising a number of brightness or speed steps.
  3. Check which pins share a timer so changing one frequency does not silently retune another output.
  4. Keep motor PWM out of the audible range where possible, and use a proper driver stage rather than the pin itself.
  5. For a PWM DAC, place the filter cutoff at least a decade below the PWM frequency and buffer low-impedance loads.
  6. Measure the actual frequency and duty on a scope or logic analyser, since requested and delivered values can differ.

PWM rewards thinking about the load first and the code second. Once you know whether a device averages the waveform or reads individual pulses, and how much resolution your timer clock can afford at the frequency you need, the right settings mostly fall out of the arithmetic.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments