Skip to main content

Subsection 11.1.3 Setting Speed: Pulse-Width Modulation

The other half of the problem is speed, and a motor’s steady speed follows the average voltage across it. Here too a GPIO pin looks unpromising: its output is either fully HIGH (3.3 V) or fully LOW (0 V), with nothing in between, so it cannot hold an average of, say, a third of the supply. What it can do is switch between HIGH and LOW very quickly, and that turns out to be enough.
Pulse-Width Modulation (PWM) switches the output between HIGH and LOW at a fixed frequency and varies the fraction of each period it spends HIGH. That fraction is the duty cycle, and it sets the average voltage: a 100% duty cycle holds the full supply continuously, a 50% duty cycle spends equal time HIGH and LOW and averages half the supply, and a 0% duty cycle holds LOW and averages nothing. As long as the switching is fast enough, the motor’s own mechanical inertia smooths the pulses out, and the motor turns as though it were driven by that steady average. This is the same trick we used to dim the seven-segment display: there it was your eye, rather than a spinning mass, that did the averaging.
One thing makes PWM practical to use: the hardware timers from Day 8 can produce the switching waveform entirely on their own. Once the timer is set up and given a duty cycle, it generates the PWM signal without any further attention from the CPU, which is then free to do other work. We will look at how to set the timer up for this in class; for now the idea to hold onto is that the duty cycle sets the average voltage, and the average voltage sets the speed.