---
title: PWM for LEDs and motors
heading: Analog-looking control from a digital pin
eyebrow: C12 · Lesson 21 · PWM for LEDs and motors
xp: 40
---

::: hook
A digital pin is either on or off, yet a microcontroller dims LEDs smoothly and runs motors at any speed. The trick is **pulse-width modulation**: switch the pin on and off thousands of times a second and vary the fraction of each period it spends on, the **duty cycle**. The eye averages the flicker into brightness; a motor's inductance and inertia average the pulses into a steady current and speed. The PWM peripheral does the switching in hardware, so the processor only sets a number when it wants a change.
:::

::: play
- A potentiometer on ADC0 sets the duty cycle of two PWM channels: the LED on P0 and the motor on P3. Move the pot slider and run again: the LED's brightness and the motor's speed follow it.
- At 20 kHz the timeline can't draw each pulse, so it labels the lane with the PWM's frequency and duty. The rpm lane shows the motor speeding up to its new speed over a few tenths of a second.
- Both channels share one frequency: this board's PWM, like many, has one period register for all four channels.
:::
:::

```sim board
lang: micropython
attach: led P0 | white
attach: motor P3 | rpm 6000
attach: pot ADC0 = 1.0 V
scope: P0, P3, rpm
run: 1 s
code:
from machine import Pin, PWM, ADC
import time

led = PWM(Pin(0), freq=20000)
motor = PWM(Pin(3), freq=20000)   # all channels share one frequency
pot = ADC(0)

while True:
    duty = pot.read_u16()          # 0..65535
    led.duty_u16(duty)
    motor.duty_u16(duty)
    time.sleep_ms(20)
```

::: predict
## A motor rated for 12 V is driven from 12 V through a transistor switched by PWM at 60% duty. What average voltage does it see?

- [ ] 12 V
- [x] 7.2 V
- [ ] 4.8 V
- [ ] 6 V

::: reveal
7.2 V: the average of a square wave between 0 and 12 V is the duty cycle times 12 V. The motor's winding inductance smooths the current, so it behaves almost as if driven by a steady 7.2 V, running at roughly 60% of its full speed, while the transistor wastes little power because it's always fully on or fully off.
:::
:::

::: nameit
## Duty and average

A pin switching between 0 and V with duty cycle D averages

$$\bar V = D\,V$$

and an LED driven that way averages D times its full current.

## The peripheral

The PWM counts from 0 to PERIOD − 1 in clock cycles and holds each channel's pin high for its first DUTY counts:

$$f_\text{PWM} = \frac{f_\text{clk}}{\text{PERIOD}}, \qquad D = \frac{\text{DUTY}}{\text{PERIOD}}$$

DUTY can only take PERIOD + 1 values, so the **resolution** is $\log_2(\text{PERIOD})$ bits: faster PWM means coarser steps. At 20 kHz, PERIOD = 500 counts, about 9 bits.

| | |
|---|---|
| C | `PWM_PERIOD = 500; PWM_DUTY(2) = 150; PWM_CTRL \|= 1 << 2;` (channel 2 on P2) |
| MicroPython | `p = PWM(Pin(2), freq=20000)`, then `p.duty_u16(d)` with d from 0 to 65535 |

## Choosing the frequency

- **LEDs:** above about 100 Hz the eye sees no flicker (cameras may, up to a few kHz).
- **Motors:** above about 20 kHz the windings don't whine audibly; higher frequencies waste more power in the switching transistor at each edge.
- Brightness looks roughly logarithmic to the eye, so dimmers map a knob to duty through a curve (gamma correction), not linearly.
:::

::: example
## What PERIOD gives 20 kHz PWM, and how many bits of resolution does it leave?

::: solution
1. **PERIOD.**
   $$\begin{aligned} \text{PERIOD} &= \frac{10^7}{20\,000} \\ &= 500\ \text{counts} \end{aligned}$$
2. **Resolution.**
   $$\log_2 500 = 8.97$$
   just under 9 bits, 501 possible duty settings.
3. **At a lower frequency.** At 1 kHz, PERIOD = 10,000 gives over 13 bits.

**Answer:** PERIOD = 500, which leaves just under 9 bits of resolution.
:::
:::

::: example
## An LED draws 3.94 mA when on. At 30% duty, what's its average current?

::: solution
1. **Scale by the duty.**
   $$0.3 \times 3.94\ \text{mA} = 1.18\ \text{mA}$$
2. **Compare with a resistor.** Dimming with PWM saves power in proportion, unlike dimming with a resistor, which wastes the rest as heat.

**Answer:** 1.18 mA on average.
:::
:::

::: example
## A hobby servo needs 50 Hz PWM with pulses from 1 ms to 2 ms. What PERIOD and what DUTY for the center, 1.5 ms?

::: solution
1. **PERIOD for 50 Hz.**
   $$\begin{aligned} \text{PERIOD} &= \frac{10^7}{50} \\ &= 200\,000\ \text{counts} \end{aligned}$$
2. **DUTY for the center.** A 1.5 ms pulse is 15,000 counts.
3. **The usable range.** 10,000 to 20,000 counts is only 5% of the period, but that's still 10,000 steps, far finer than a servo can follow.

**Answer:** PERIOD = 200,000 and DUTY = 15,000.
:::
:::

::: check
given: V = 3.3 | 5 | 12 | 24; D = 15 | 40 | 75
answer: D/100*V
unit: V
tolerance: 0.5%

## A pin switches between 0 and {V} V at {D}% duty. What's the average voltage?

::: right
Right. $DV$ = {answer} V.
:::

::: misses
- [any] Not yet. Duty times the high voltage.
:::
:::

::: check
given: f = 1000 | 20000 | 50000 | 250000
answer: 1e7/f
tolerance: 0

## What PWM PERIOD, in clock cycles, gives {f} Hz?

::: right
Right. $f_\text{clk}/f$ = {answer}.
:::

::: misses
- [1e7/f - 1] This PWM counts 0 to PERIOD − 1, so PERIOD is the whole count.
- [any] Not yet. $10^7/f$.
:::
:::

::: check
given: P = 200 | 500 | 10000 | 65536
answer: log(P)/log(2)
tolerance: 0.5%

## With PERIOD = {P}, how many bits of duty resolution does the PWM have?

::: right
Right. $\log_2 P$ = {answer} bits.
:::

::: misses
- [log(P)] That's log base 10; resolution in bits is $\log_2$.
- [any] Not yet. $\log_2(\text{PERIOD})$.
:::
:::

::: check
given: P = 500 | 1000 | 10000; D = 12.5 | 40 | 90
answer: D/100*P
tolerance: 0

## With PERIOD = {P}, what DUTY value gives {D}%?

::: right
Right. {answer} counts.
:::

::: misses
- [any] Not yet. {D}% of the period, in counts.
:::
:::

::: check
given: d = 16384 | 32768 | 49152
answer: 100*d/65535
unit: %
tolerance: 0.2%

## MicroPython's `duty_u16(d)` takes d from 0 to 65535. What duty cycle is `duty_u16({d})`?

::: right
Right. {answer}%.
:::

::: misses
- [any] Not yet. d out of 65,535.
:::
:::

::: check
kind: choice

## A motor driven by 2 kHz PWM whines audibly. What change fixes it?

- [ ] Lower the PWM frequency to 500 Hz
- [x] Raise the PWM frequency above about 20 kHz
- [ ] Use 100% duty
- [ ] Add a pull-up resistor

::: misses
- [1] That moves the whine lower, where it's still audible.
- [3] Full duty stops the switching but loses speed control.
- [4] A pull-up has nothing to do with the sound.
:::
:::

::: check
kind: micropython
given: f = 1000 | 5000 | 20000; D = 25 | 50 | 80
attach: led P1
run: 0.05
expect: pwmfreq = f Hz ± 0.5%; pwmduty(1) = D % ± 0.5

## Drive the LED on P1 with PWM at {f} Hz and {D}% duty.

```micropython starter
from machine import Pin, PWM

led = Pin(1, Pin.OUT)
led.on()
```

```micropython solution
from machine import Pin, PWM

led = PWM(Pin(1), freq=f, duty_u16=D * 65535 // 100)
```

::: right
Right. `duty_u16` scales {D}% to 0..65535.
:::
:::

::: check
kind: c
given: F = 1000 | 4000 | 20000; D = 20 | 60
attach: motor P2
run: 0.5
expect: pwmfreq = F Hz ± 0.1%; pwmduty(2) = D % ± 0.5; rpm = 60*D ± 300

## Run the motor on P2 at `D`% ({D}%) of full speed using PWM channel 2 at `F` Hz ({F} Hz), writing the PWM registers directly.

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1 << 2;
    GPIO_SET = 1 << 2;
    return 0;
}
```

```c solution
#include "board.h"

int main(void) {
    uint32_t period = F_CPU / F;
    PWM_PERIOD = period;
    PWM_DUTY(2) = period * D / 100;
    PWM_CTRL |= 1 << 2;
    return 0;
}
```

::: right
Right. Period from the clock, duty as a fraction of the period, then enable the channel.
:::
:::

::: check
kind: parts
given: f = 50 | 1000 | 25000

## PWM on the 10 MHz board runs at {f} Hz.

::: part
answer: 1e7/f
tolerance: 0.5%

### What PERIOD?

::: misses
- [any] $10^7/f$.
:::
:::

::: part
answer: log(1e7/f)/log(2)
tolerance: 0.5%

### How many bits of duty resolution?

::: misses
- [any] $\log_2$ PERIOD.
:::
:::
:::

::: check
kind: parts
given: P = 500 | 10000 | 200000; d = 10 | 37.5 | 75; I = 3.9 | 20

## PWM with PERIOD = {P} drives a load that draws {I} mA when on, at {d}% duty.

::: part
answer: round(P*d/100)
tolerance: 0

### What DUTY value?

::: misses
- [any] PERIOD × duty.
:::
:::

::: part
answer: I*d/100
unit: mA
tolerance: 0.5%

### What average current?

::: misses
- [any] On-current × duty.
:::
:::
:::

::: explain
## Why does PWM control a motor's speed efficiently, while a series resistor that drops the voltage wastes power?

::: model
A resistor in series reduces the motor's voltage by dissipating the difference as heat: at half speed it burns roughly as much power as the motor uses. With PWM the switching transistor is either fully on, with almost no voltage across it, or fully off, with almost no current through it, so in both states it dissipates very little; only the brief transitions cost energy. The motor's inductance and inertia average the pulses into a steady current and speed proportional to the duty cycle, so the average power delivered is controlled by timing, not by burning off the excess.
:::
:::

::: practice

::: check
given: V = 9 | 48; D = 30 | 85
answer: D/100*V
unit: V
tolerance: 0.5%

## Average of {V} V at {D}% duty?

::: misses
- [any] $DV$.
:::
:::

::: check
given: f = 1000 | 2000 | 4000 | 5000 | 10000 | 20000 | 25000 | 40000
answer: 1e7/f
tolerance: 0

## PERIOD for {f} Hz?

::: misses
- [any] $f_\text{clk}/f$.
:::
:::

::: check
given: P = 256 | 500 | 1000 | 1024 | 4096 | 10000
answer: log(P)/log(2)
tolerance: 0.5%

## Resolution bits for PERIOD {P}?

::: misses
- [any] $\log_2 P$.
:::
:::
:::
