Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Interrupts and Timers

Timers, Counters and PWM

Learn how hardware timers count clock ticks, how prescalers and reload values set the period, and how compare registers generate PWM signals for LEDs and motors.

Almost every embedded program needs to know about time: blink an LED twice a second, read a sensor every 10 ms, time a pulse, or dim a lamp. A CPU loop full of delay() calls can do some of this, but it wastes the processor and drifts. The proper tool is a hardware timer: a counter inside the microcontroller that counts clock pulses by itself while the CPU does other things, and can raise an interrupt or toggle a pin when it reaches a chosen value.

This lesson explains how a timer is built, how to calculate the prescaler and reload value for a given period, and how the same counter generates PWM (pulse-width modulation), the standard way to control brightness, motor speed and servo angle with a digital pin.

The anatomy of a timer

A timer is a counter

Clock source Usually the CPU clock or a peripheral clock
Prescaler Divides the clock so counting is slower
Counter Increments on every divided tick
1 / 2

A timer has these parts, with slightly different names on each chip family:

  • Clock input. The CPU clock or a divided bus clock feeds the timer. A 16 MHz clock ticks every 62.5 ns.
  • Prescaler. A divider placed before the counter. With a prescaler of 64, the counter advances once every 64 clock cycles. This lets a 16-bit counter measure long times.
  • Counter register (CNT or TCNT). The current count. Software can read it, and often write it.
  • Auto-reload / top value (ARR or TOP). When the counter reaches this value it returns to zero. The distance between two returns is the timer's period.
  • Compare registers (CCR or OCR). When the counter equals the compare value, the hardware can set a flag, raise an interrupt, or change an output pin without any CPU involvement.
  • Capture registers. The reverse: when an input pin changes, the hardware copies the counter into a register, so you can measure the width of a pulse or the period of a signal with microsecond accuracy.

The timer width matters. An 8-bit counter wraps after 256 ticks, a 16-bit counter after 65,536, a 32-bit counter after about 4.29 billion.

The period formula

If the timer clock is f_clk, the prescaler divides by P, and the counter counts from 0 up to ARR (so it has ARR + 1 states), the update frequency is

TEXT
f_update = f_clk / (P * (ARR + 1))

Many chips store P - 1 and ARR in the registers, so check your datasheet for the off-by-one: forgetting it makes every period slightly wrong. For a 1 ms tick on a 16 MHz clock you need P * (ARR + 1) = 16,000. With P = 1 that is ARR = 15,999, which fits in a 16-bit counter. For a 1 Hz tick you need P * (ARR + 1) = 16,000,000, which does not fit in 16 bits at P = 1, so a larger prescaler is required.

The program below searches for a prescaler and reload value for several targets. It prefers the smallest prescaler that gives the smallest error, which also keeps the counter resolution high.

C Calculate prescaler and reload values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The 1 Hz case needs a prescaler of 250 here, so the counter ticks at 64 kHz. The 440 Hz case shows the other outcome: no divider gives exactly 440 Hz from 8 MHz, so you accept a tiny error (0.004 Hz, inaudible). Real designs pick crystal frequencies that divide nicely (32.768 kHz for a real-time clock, or 8 MHz and 12 MHz for round numbers), use a 32-bit timer, or count several timer ticks in software.

Three common timer jobs

1. A periodic tick. Configure the timer for, say, 1 ms and enable its update interrupt. The ISR increments a global ms_ticks counter. Everything else (timeouts, blinking, scheduling) can be built on that single tick, as you will see in debouncing and software timers and in the cooperative scheduler.

2. Measuring time with input capture. An ultrasonic distance sensor answers with a pulse whose width is proportional to distance. The capture hardware stores the counter value on the rising edge and again on the falling edge. The difference, multiplied by the tick duration, is the pulse width, with no software jitter.

3. Generating output signals. The compare register can toggle a pin when the counter matches. Toggling at a fixed frequency produces a square wave (a buzzer tone). Changing the compare value from the interrupt produces more complex waveforms.

PWM: analog behavior from a digital pin

A digital pin is either high or low. To get an average value in between, switch it quickly and vary the proportion of time spent high. That proportion is the duty cycle:

TEXT
duty = time_high / period

At 25% duty a 5 V pin has an average of about 1.25 V. An LED looks dimmer, a DC motor turns slower, and the switching is fast enough that the load's own inertia (or your eye) smooths it out.

In hardware PWM the counter runs from 0 to ARR. The output pin is high while CNT < CCR and low afterwards. So:

  • the frequency is set by the prescaler and ARR (the same formula as above);
  • the duty cycle is CCR / (ARR + 1);
  • the resolution is the number of distinct duty steps, ARR + 1.

Frequency and resolution compete: for a fixed clock, a higher PWM frequency means a smaller ARR and fewer duty steps. LED dimming is fine at 1 kHz and up (no flicker). Motors are often driven above 20 kHz so the whistle is inaudible. Hobby servos need 50 Hz with a pulse between about 1 ms and 2 ms.

C Draw PWM waveforms from a compare value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On real hardware you would write those numbers into the compare register and the chip does the rest, even while the CPU is asleep or busy elsewhere. A board-specific example (read-only) for an AVR in fast PWM mode:

C
// Read-only AVR sketch: 8-bit fast PWM on OC0A (pin PD6), about 976 Hz at 16 MHz
DDRD  |= (1 << PD6);                       // pin as output
TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);   // non-inverting fast PWM
TCCR0B = (1 << CS01) | (1 << CS00);        // prescaler 64
OCR0A  = 64;                               // duty = 64 / 256 = 25%

Common mistakes

  • Off-by-one in the reload value. The counter has ARR + 1 states.
  • Overflow in the math. 16000000 * 1000 does not fit in a 32-bit int. Use uint32_t or uint64_t for clock math, as the simulation does.
  • Changing the compare value mid-period. Without a shadow (preload) register this can glitch the output. Enable preload so the new value takes effect at the next update.
  • Expecting an exact frequency. Always compute the actual value and the error from the divider you can really set.
  • Forgetting to enable the timer's clock. On most chips peripherals are powered down until you enable their clock in a reset-and-clock register.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A timer runs from a 16 MHz clock with prescaler 1 and ARR = 15999. What is its update frequency?

    The counter has ARR + 1 = 16000 states, so 16,000,000 / 16,000 = 1000 Hz, a 1 ms period.
  2. 2. In PWM with ARR = 99 and CCR = 30, what is the duty cycle?

    Duty is CCR / (ARR + 1) = 30 / 100 = 30%.
  3. 3. What is the job of a prescaler?

    Dividing the input clock stretches the time the counter needs to cover its range, allowing long periods.
  4. 4. Which feature measures the width of an external pulse without software jitter?

    Input capture copies the counter into a register in hardware at the exact moment an edge arrives.

Summary

  • A hardware timer is a counter driven by a divided clock; it wraps at a reload value and can raise events without CPU help.
  • Period = P * (ARR + 1) / f_clk; check the datasheet for the off-by-one in register values.
  • Compare registers generate outputs and delays; capture registers measure external pulses.
  • PWM sets duty with the compare value and frequency with prescaler and reload; frequency and resolution trade off against each other.

Next: Volatile and Shared Data