C12 · Lesson 11 · Hardware timers
Counting clock cycles in hardware, so the program doesn't have to
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.
- 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.
Predict
The timer runs with PRESCALE = 99 and TOP = 999. How often does it wrap?
Every 10 ms: it counts at kHz, 10 µs per count, and wraps after 1000 counts. P0, toggling at each wrap, would then square-wave at 50 Hz.
Name it
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
A larger prescaler reaches longer periods; a smaller one gives finer resolution, since the period can only change in steps of one count, . 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.
Worked example
Choose PRESCALE and TOP for a 1 ms wrap.
Show the solution
- Pick the prescaler. With PRESCALE = 9 the timer counts at 1 MHz, 1 µs per count.
- Count to 1 ms. 1 ms needs 1000 counts, so
- Another choice. PRESCALE = 0 and TOP = 9999 works too, with finer resolution.
Answer PRESCALE = 9 and TOP = 999 (or PRESCALE = 0 and TOP = 9999).
Worked 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?
Show the solution
- Cycles per wrap.
- Round to a whole TOP. TOP must be a whole number, so TOP = 11,363 gives 11,364 cycles per wrap.
- The tone. Two wraps make one cycle of the tone:
- 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.
Worked 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?
Show the solution
- Subtract modulo .
- Convert to time. At 1 MHz that's 32 µs.
- 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
A timer has PRESCALE = 9 and TOP = 99, on the 10 MHz clock. How long between wraps?
Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.
Check
At what rate does a timer with PRESCALE = 99 count?
Write units the way you normally would: 1.5 kHz, 1500 Hz and 0.0015 MHz are the same answer.
Check
With PRESCALE = 9, what TOP makes the timer wrap every 2 ms?
Check
With PRESCALE = 9, by how much can the period be adjusted, at the finest?
Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.
Check
A pin toggles at each timer wrap, making a square wave. With PRESCALE = 0, what TOP gives the closest to 440 Hz?
Check
A 32-bit cycle counter read 4,294,967,000 at one event and 1000 at the next, having wrapped through zero in between. How many cycles passed? (This is what t2 - t1 gives in unsigned 32-bit arithmetic.)
Check
Using the hardware timer and its flag (not a delay loop), toggle P0 every MS (5) ms.
C on the course's RISC-V board (10 MHz, no floating point). #include "board.h" for the registers; print(x) shows a number. Tab indents; press Esc and then Tab to move on.
Check
Blink the LED on P0 at 5 Hz using machine.Timer with a callback, not a sleeping loop.
MicroPython on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.
Check
The timer wraps at Hz, with PRESCALE = 9.
(a)
What TOP gives 100 Hz (nearest)?
(b)
What frequency does that give exactly?
Write units the way you normally would: 1.5 Hz, 1500 mHz and 0.0015 kHz are the same answer.
Check
A 16-bit counter ticking at 1 MHz read 65000 at the start and 16 at the end.
(a)
How long was the interval?
Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.
(b)
What is the longest interval it can time unambiguously?
Explain why
Why is a hardware timer a better way to time a periodic task than a delay loop?
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
Keep practicing
13 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.