A microcontroller pin is either on or off. Yet robots dim lights and run motors at half speed. The trick is to switch very fast.
Key idea
Pulse-width modulation (PWM) switches a pin fully on and off many times a second. The duty cycle is the fraction of time it is on. The average voltage is the duty cycle times the supply: $V_{\text{avg}} = D \times V$.
Why it works
Switching wastes very little power: when the switch is fully on or fully off, almost nothing heats up inside it. A motor's inertia smooths the pulses into a steady speed, and your eye smooths a blinking LED into a dimmer glow.
Worked example: Average voltage
A 5 V pin runs at 30% duty.
- $0.30 \times 5 = 1.5\ \text{V}$ on average.
Answer: 1.5 V.
Worked example: An 8-bit setting
Arduino's analogWrite takes 0 to 255. What duty cycle is 64?
- $64 / 255 \approx 0.251$.
Answer: About 25%.
Common mistake
Thinking PWM makes a lower steady voltage. The pin is always at full voltage or zero; only the average is lower. That is why a motor needs a motor driver: the pin itself cannot supply a motor's current.
Hands-on: fade an LED and spin a motor
Parts (about \$15 to \$25 beyond the starter kit)
- A small DC gear motor and a dual motor driver board (an H-bridge)
- A battery holder for 4 AA cells for the motor, kept separate from the board's USB power, with grounds joined
Fade an LED from 0 to 255 in a loop. Then wire the motor through the driver and ramp it up the same way. Notice that a motor does not start turning until the duty cycle is high enough to beat friction.
Safety. Keep fingers and hair clear of the motor's shaft and gears while it runs, and switch the power off before touching anything.