---
title: Hardware timers
heading: Counting clock cycles in hardware, so the program doesn't have to
eyebrow: C12 · Lesson 11 · Hardware timers
xp: 40
---

::: hook
A delay loop keeps the processor busy doing nothing, and its timing depends on how the compiler wrote the loop. A **timer** is a counter built into the chip that counts clock cycles on its own, whatever the program is doing. Set how fast it counts (the **prescaler**) and where it wraps around (the **top** value), and it marks out exact intervals: it can set a flag, raise an interrupt (next lesson) or drive a pin. Nearly every periodic job in firmware, from blinking to sampling to motor control, runs from a timer.
:::

::: play
- The timer counts at 10 MHz/(PRESCALE + 1) and wraps after TOP + 1 counts, setting a flag. The program waits for the flag, clears it and toggles P0, so P0's period is two wraps.
- With PRESCALE = 9 and TOP = 999, the timer counts at 1 MHz and wraps every millisecond: P0 is a 500 Hz square wave. Check it on the timeline.
- Change TOP to 499, or PRESCALE to 99, and predict the new period before you run it.
:::
:::

```sim board
lang: c
attach: led P0 | green
scope: P0 | 0..10 ms
run: 20 ms
show: debug
code:
#include "board.h"

#define PRESCALE 9      // count at 10 MHz / (9 + 1) = 1 MHz
#define TOP 999         // wrap after 1000 counts: every 1 ms

int main(void) {
    GPIO_DIR = 1 << 0;
    TIMER_PRESCALE = PRESCALE;
    TIMER_TOP = TOP;
    TIMER_CTRL = TIMER_RUN;
    while (1) {
        while (!(TIMER_FLAGS & 1))   // wait for the wrap
            ;
        TIMER_FLAGS = 1;             // clear the flag (write 1 to clear)
        GPIO_TOGGLE = 1 << 0;
    }
}
```

::: predict
## The timer runs with PRESCALE = 99 and TOP = 999. How often does it wrap?

- [ ] Every 1 ms
- [x] Every 10 ms
- [ ] Every 100 ms
- [ ] Every 99.9 µs

::: reveal
Every 10 ms: it counts at $10\text{ MHz}/100 = 100$ kHz, 10 µs per count, and wraps after 1000 counts. P0, toggling at each wrap, would then square-wave at 50 Hz.
:::
:::

::: nameit
## Prescaler and top

The counter advances once every PRESCALE + 1 clock cycles, counts from 0 up to TOP, then wraps to 0 and sets its flag. The time between wraps is

$$T = \frac{(\text{PRESCALE} + 1)(\text{TOP} + 1)}{f_\text{clk}}$$

A larger prescaler reaches longer periods; a smaller one gives finer resolution, since the period can only change in steps of one count, $(\text{PRESCALE} + 1)/f_\text{clk}$. To hit a target period, pick the smallest prescaler whose TOP fits, then round TOP; the error is at most half a count.

## Flags

A flag stays set until the program clears it. Here, writing 1 to a flag bit clears it (**write-1-to-clear**), so clearing one flag can't disturb another. A program can **poll** the flag, as above, or let it raise an interrupt (lesson 12) and do something else meanwhile.

## Reading time

The running count (`TIMER_COUNT`) and the system cycle counter (`SYS_CYCLES`) give timestamps: the time between two events is the difference of two readings, computed in unsigned arithmetic so it stays right across a wrap.

## In MicroPython

`machine.Timer(period=500, mode=Timer.PERIODIC, callback=f)` calls f every 500 ms; on this board it runs as a soft interrupt, between Python statements.
:::

::: example
## Choose PRESCALE and TOP for a 1 ms wrap.

::: solution
1. **Pick the prescaler.** With PRESCALE = 9 the timer counts at 1 MHz, 1 µs per count.
2. **Count to 1 ms.** 1 ms needs 1000 counts, so
   $$\text{TOP} = 999$$
3. **Another choice.** PRESCALE = 0 and TOP = 9999 works too, with finer resolution.

**Answer:** PRESCALE = 9 and TOP = 999 (or PRESCALE = 0 and TOP = 9999).
:::
:::

::: example
## A buzzer pin should toggle at 880 Hz, making a 440 Hz tone. With PRESCALE = 0, what TOP, and how close is the tone?

::: solution
1. **Cycles per wrap.**
   $$\frac{10^7}{880} = 11\,363.6$$
2. **Round to a whole TOP.** TOP must be a whole number, so TOP = 11,363 gives 11,364 cycles per wrap.
3. **The tone.** Two wraps make one cycle of the tone:
   $$\begin{aligned} f &= \frac{10^7}{2 \times 11\,364}\ \text{Hz} \\ &= 439.986\ \text{Hz} \end{aligned}$$
4. **How close.** That's 0.003% flat: far better than anyone can hear.

**Answer:** TOP = 11,363, which makes 439.986 Hz, 0.003% flat.
:::
:::

::: example
## A 16-bit free-running counter ticks at 1 MHz. It read 0xFFF0 at the start of an event and 0x0010 at the end. How long was the event?

::: solution
1. **Subtract modulo $2^{16}$.**
   $$\begin{aligned} &(\text{0x0010} - \text{0xFFF0}) \bmod 65\,536 \\ &= 32\ \text{counts} \end{aligned}$$
2. **Convert to time.** At 1 MHz that's 32 µs.
3. **Do it in C.** Computing `(uint16_t)(end - start)` gives the right answer across the wrap automatically, as long as the event is shorter than one full turn, 65.5 ms.

**Answer:** the event lasted 32 µs.
:::
:::

::: check
given: P = 0 | 9 | 99 | 999; N = 99 | 999 | 4999
answer: (P + 1)*(N + 1)/1e7*1000
unit: ms
tolerance: 0.05%

## A timer has PRESCALE = {P} and TOP = {N}, on the 10 MHz clock. How long between wraps?

::: right
Right. $(\text{PRESCALE} + 1)(\text{TOP} + 1)/f$ = {answer} ms.
:::

::: misses
- [P*N/1e7*1000] Both count from zero: use PRESCALE + 1 and TOP + 1.
- [any] Not yet. $(P + 1)(N + 1)/10^7$.
:::
:::

::: check
given: P = 9 | 99 | 999
answer: 1e7/(P + 1)/1000
unit: kHz
tolerance: 0.05%

## At what rate does a timer with PRESCALE = {P} count?

::: right
Right. $10\text{ MHz}/(P + 1)$ = {answer} kHz.
:::

::: misses
- [1e7/P/1000] Divide by PRESCALE + 1.
- [any] Not yet. $f/(P + 1)$.
:::
:::

::: check
given: P = 9 | 99; T = 2 | 20 | 250
answer: T*1e-3*1e7/(P + 1) - 1
tolerance: 0

## With PRESCALE = {P}, what TOP makes the timer wrap every {T} ms?

::: right
Right. TOP = {answer}.
:::

::: misses
- [T*1e-3*1e7/(P + 1)] That's the number of counts; TOP is one less, since it counts from 0.
- [any] Not yet. Counts per period, minus 1.
:::
:::

::: check
given: P = 0 | 9 | 99
answer: (P + 1)/1e7*1e6
unit: µs
tolerance: 0.5%

## With PRESCALE = {P}, by how much can the period be adjusted, at the finest?

::: right
Right. One count: {answer} µs.
:::

::: misses
- [any] Not yet. One count lasts $(P + 1)/f$.
:::
:::

::: check
given: f = 50 | 440 | 1000 | 2500
answer: round(1e7/(2*f)) - 1
tolerance: 0

## A pin toggles at each timer wrap, making a square wave. With PRESCALE = 0, what TOP gives the closest to {f} Hz?

::: right
Right. A wrap every half period, $10^7/(2f)$ cycles, rounded: TOP = {answer}.
:::

::: misses
- [round(1e7/f) - 1] Two wraps make one period: the pin toggles on each.
- [any] Not yet. Half a period in cycles, minus 1.
:::
:::

::: check
given: t2 = 204 | 1000 | 30000
answer: t2 + 296
tolerance: 0

## A 32-bit cycle counter read 4,294,967,000 at one event and {t2} at the next, having wrapped through zero in between. How many cycles passed? (This is what `t2 - t1` gives in unsigned 32-bit arithmetic.)

::: right
Right. 296 cycles to reach $2^{32}$, then {t2} more: {answer}. Unsigned subtraction wraps the same way the counter does, so it gets this right.
:::

::: misses
- [t2 - 4294967000] Signed arithmetic gives a large negative number; the counter wrapped, so count up to $2^{32}$ and on.
- [any] Not yet. Cycles up to the wrap, plus {t2}.
:::
:::

::: check
kind: c
given: MS = 2 | 5 | 8
attach: led P0
run: 0.1
expect: period(P0) = 2*MS ms ± 0.1%

## Using the hardware timer and its flag (not a delay loop), toggle P0 every `MS` ({MS}) ms.

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

int main(void) {
    GPIO_DIR = 1 << 0;
    while (1) {
        GPIO_TOGGLE = 1 << 0;
    }
}
```

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

int main(void) {
    GPIO_DIR = 1 << 0;
    TIMER_PRESCALE = 9;
    TIMER_TOP = MS * 1000 - 1;
    TIMER_CTRL = TIMER_RUN;
    while (1) {
        while (!(TIMER_FLAGS & 1))
            ;
        TIMER_FLAGS = 1;
        GPIO_TOGGLE = 1 << 0;
    }
}
```

::: right
Right. The timer measures the interval exactly, however long the loop takes.
:::
:::

::: check
kind: micropython
given: f = 2 | 5 | 10
attach: led P0
run: 2
expect: period(P0) = 1000/f ms ± 0.5%

## Blink the LED on P0 at {f} Hz using `machine.Timer` with a callback, not a sleeping loop.

```micropython starter
from machine import Pin, Timer
import time

led = Pin(0, Pin.OUT)
while True:
    time.sleep_ms(100)
```

```micropython solution
from machine import Pin, Timer
import time

led = Pin(0, Pin.OUT)
Timer(freq=2 * f, mode=Timer.PERIODIC, callback=lambda t: led.toggle())
while True:
    time.sleep_ms(1000)
```

::: right
Right. The timer toggles at twice the blink frequency: one toggle on, one off.
:::
:::

::: check
kind: parts
given: P = 0 | 9 | 99; f = 100 | 1000 | 8000

## The timer wraps at $10^7/((\text{PRESCALE} + 1)(\text{TOP} + 1))$ Hz, with PRESCALE = {P}.

::: part
answer: round(1e7/((P + 1)*f)) - 1
tolerance: 0

### What TOP gives {f} Hz (nearest)?

::: misses
- [round(1e7/((P + 1)*f))] TOP counts from 0, so subtract 1.
- [any] $10^7/((P + 1)f) - 1$, rounded.
:::
:::

::: part
answer: 1e7/((P + 1)*round(1e7/((P + 1)*f)))
unit: Hz
tolerance: 0.01%

### What frequency does that give exactly?

::: misses
- [any] Put TOP back into the formula.
:::
:::
:::

::: check
kind: parts
given: a = 65520 | 65000 | 61000; b = 16 | 300 | 900

## A 16-bit counter ticking at 1 MHz read {a} at the start and {b} at the end.

::: part
answer: b - a + 65536*step(a - b)
unit: µs
tolerance: 0

### How long was the interval?

::: misses
- [b - a] Subtract modulo 65,536.
- [any] $(b - a) \bmod 65536$.
:::
:::

::: part
answer: 65536/1000
unit: ms
tolerance: 0.5%

### What is the longest interval it can time unambiguously?

::: misses
- [any] One full turn.
:::
:::
:::

::: explain
## Why is a hardware timer a better way to time a periodic task than a delay loop?

::: model
A timer counts the clock in dedicated hardware, so its interval depends only on the clock and its two settings, not on how many instructions the program runs, which compiler optimizations it got, or whether an interrupt stole some cycles. A delay loop's length is however long its instructions happen to take, which changes with the compiler, the code around it and interrupts, and the processor can do nothing else while it waits. With a timer, the program can do other work, or sleep, and just respond to the flag or the interrupt when the interval is up, and the intervals never accumulate error.
:::
:::

::: practice

::: check
given: P = 4 | 49; N = 199 | 1999
answer: (P + 1)*(N + 1)/1e7*1000
unit: ms
tolerance: 0.5%

## Wrap period with PRESCALE {P}, TOP {N}?

::: misses
- [any] $(P + 1)(N + 1)/f$.
:::
:::

::: check
given: P = 9 | 999; T = 5 | 100
answer: T*1e-3*1e7/(P + 1) - 1
tolerance: 0

## TOP for {T} ms with PRESCALE {P}?

::: misses
- [any] Counts minus 1.
:::
:::

::: check
given: f = 100 | 200 | 440 | 500 | 1000 | 2000 | 3000 | 5000
answer: round(1e7/(2*f)) - 1
tolerance: 0

## TOP (PRESCALE 0) for a {f} Hz square wave?

::: misses
- [any] Half period in cycles, minus 1.
:::
:::
:::
