Timers and pulse-width modulation
How hardware timers count clock pulses to measure time, and how pulse-width modulation uses fast on–off switching to dim LEDs and control motor speed.
Lesson 4 of 6 · 30 min · Self-paced · Free
Precise time without the CPU
A robot arm's joint motor needs its power adjusted smoothly, not just switched fully on or off. A control loop must run exactly every millisecond. A status light should fade gently rather than flash. All of these depend on timers, among the most useful peripherals on any microcontroller. Timers count independently of the CPU, so timing stays accurate even while your program is busy. And one of their most important jobs is producing PWM, a trick that lets a digital pin behave almost like an adjustable voltage.
How a timer works
A timer is a hardware counter, a register built from flip-flops, just like the counters in the sequential logic lesson. On every tick it adds one. Ticks come from the system clock, usually through a prescaler that divides the clock down so the counter does not race through its range too quickly.
When the counter reaches its maximum it overflows and starts again from zero. Many timers can also compare the count with a value you choose and do something when they match, such as setting a flag, triggering an interrupt or flipping a pin. This is a compare match.
Worked example: a 1 ms tick
A chip runs at 16 MHz. Set the prescaler to 64:
tick rate = 16 000 000 / 64 = 250 000 ticks per second
tick period = 1 / 250 000 = 4 µsTo mark every millisecond, count 1 ms / 4 µs = 250 ticks. Configure a compare match at the 250th tick (count 249, since the count starts at 0) and reset the counter each time. You now have a clock that ticks exactly every millisecond, the basis of the non-blocking timing you will meet in the programming foundations module.
How long can a 16-bit timer count with that prescaler before overflowing? It has 65,536 values:
65 536 × 4 µs = 262 144 µs ≈ 262 msA bigger prescaler stretches the range but makes each tick coarser. That trade-off between range and resolution shows up constantly in embedded design.
Pulse-width modulation
A GPIO pin can only be high or low. But suppose you switch it on and off very quickly: on for one quarter of the time, off for three quarters, thousands of times per second. Anything slow to respond, such as your eye looking at an LED or the heavy rotor of a motor, experiences the average.
That is pulse-width modulation (PWM). Two numbers describe it:
- Frequency: how many on–off cycles happen per second. The period is 1 / frequency.
- Duty cycle: the fraction of each period the signal is high, usually given as a percentage.
The average voltage is:
V_average = duty cycle × V_highFor a 3.3 V pin at 25 % duty: 0.25 × 3.3 = 0.825 V on average. At 0 % the pin is always low; at 100 % always high.
How a timer makes PWM
A PWM timer counts from 0 up to a top value, then restarts. The pin is high while the count is below a compare value and low once it passes it. Moving the compare value changes the duty cycle; changing the clock, prescaler or top changes the frequency.
frequency = clock / prescaler / (top + 1)
duty cycle ≈ compare / (top + 1)The exact formula varies slightly between timer modes and chips, so the datasheet has the final word. This portable C program does the arithmetic; it runs on any computer:
#include <stdio.h>
int main(void) {
const double clock_hz = 16000000.0; /* 16 MHz system clock */
const int prescaler = 64; /* timer ticks once every 64 clocks */
const int top = 255; /* counter runs 0, 1, ... 255, 0, ... */
double tick_hz = clock_hz / prescaler;
double pwm_hz = tick_hz / (top + 1);
int duty_percent = 25;
int compare = (top + 1) * duty_percent / 100;
double average_v = 3.3 * compare / (top + 1);
printf("Timer tick: %.0f Hz\n", tick_hz);
printf("PWM frequency: %.1f Hz\n", pwm_hz);
printf("Compare value for %d%% duty: %d\n", duty_percent, compare);
printf("Average of a 3.3 V signal: %.3f V\n", average_v);
return 0;
}Output:
Timer tick: 250000 Hz
PWM frequency: 976.6 Hz
Compare value for 25% duty: 64
Average of a 3.3 V signal: 0.825 VWith top = 255, there are 256 possible compare values, so this PWM has 8-bit resolution: the duty cycle moves in steps of 1/256, about 0.4 %.
Dimming an LED
At around 1 kHz, the LED flickers far too fast for most people to see, and it simply looks dimmer. Fading is just a loop that slowly changes the duty cycle. Using illustrative functions that stand in for your board's library:
/* Illustrative only: pwm_start, pwm_set_duty and delay_ms stand in for
your board's library. Duty is in parts per thousand: 250 = 25.0 %. */
#define LED_PIN 9
int main(void) {
pwm_start(LED_PIN, 1000); /* 1 kHz PWM */
while (1) {
for (uint32_t d = 0; d <= 1000; d += 10) {
pwm_set_duty(LED_PIN, d); /* fade up */
delay_ms(10);
}
for (uint32_t d = 1000; d > 0; d -= 10) {
pwm_set_duty(LED_PIN, d); /* fade down */
delay_ms(10);
}
}
}One subtlety: our eyes do not respond to brightness linearly. Going from 10 % to 20 % duty looks like a much bigger jump than going from 80 % to 90 %. Smooth-looking fades often use a curve (sometimes called gamma correction) rather than equal steps.
Controlling motor speed
A DC motor's coil and spinning mass smooth out PWM in the same way, so its speed follows the average voltage, roughly speaking. Crucially, the GPIO pin never powers the motor. The PWM signal goes to a motor driver, such as a transistor or an H-bridge chip, which switches the motor's own supply on and off at the same duty cycle. The pin provides only the timing.
Frequency matters for motors. In the audible range, a few hundred hertz to a few kilohertz, motors often whine. Drivers are frequently run at around 20 kHz, near the upper limit of human hearing, so the noise disappears, though very high frequencies increase switching losses in the driver. As always, follow the driver's datasheet.
Hobby servos use PWM differently: they expect a pulse roughly every 20 ms (50 Hz), and the width of the pulse, typically about 1 to 2 ms, sets the angle rather than the speed.
Project
Design two PWM signals on paper
Using frequency = clock / prescaler / (top + 1) and a 16 MHz clock:
- LED dimmer. Choose a prescaler from 1, 8, 64, 256 or 1024, and a top value no greater than 255, that gives a frequency between 200 Hz and 2 kHz. Work out the compare value for 40 % duty and the average voltage on a 3.3 V pin.
- Motor driver. Find a prescaler and top value that give a frequency within 5 % of 20 kHz. How many distinct duty-cycle steps does your choice allow? Explain the trade-off between frequency and resolution.
- Optional: modify the C program in this lesson to check your answers.
This activity is calculation only. If you later try it on a real board, follow the safety text.
Deliverables
- Prescaler, top value, frequency, compare value and average voltage for the LED dimmer
- Prescaler, top value, frequency and number of duty steps for the motor signal
- Two or three sentences explaining the frequency–resolution trade-off
Adult supervision requiredAny real-hardware follow-up must be done with adult supervision, using a USB-powered board at 5 V or less. Drive LEDs through a series resistor, and drive any motor only through a proper motor driver with its own low-voltage supply, never directly from a pin. Keep fingers clear of moving parts and disconnect power before changing wiring.
Knowledge check
Check your understanding
Go further
- Pulse-width modulation (Wikipedia) ↗
Duty cycle, frequency choice and applications from LEDs to motor drives.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.