A hardware timer counts clock pulses, divided first by a prescaler. In compare (CTC) mode it resets and raises an interrupt when it reaches a compare value. The formula is:
compare value = f_clk ÷ (N × f_target) − 1
where N is the prescaler and f_target the interrupt rate. The −1 is there because the count starts at zero.
Problem 1: a 1 ms tick from a 16 MHz clock.
| Prescaler N | Timer clock | Compare value | Fits 8-bit (≤ 255)? | Fits 16-bit (≤ 65,535)? |
|---|
| 1 | 16 MHz | 15999 | No | Yes |
| 8 | 2 MHz | 1999 | No | Yes |
| 64 | 250 kHz | 249 | Yes | Yes |
On an 8-bit timer, only N = 64 works, giving a compare value of 249: 250 ticks of 4 µs each is exactly 1 ms.
Problem 2: a 1 second interrupt on a 16-bit timer.
| Prescaler N | Compare value | Fits 16-bit? |
|---|
| 64 | 249999 | No |
| 256 | 62499 | Yes |
| 1024 | 15624 | Yes |
Both 256 and 1024 work. Choose 256: the larger compare value gives finer adjustment, and both divide 16 MHz exactly, so neither introduces rounding error.
The check that earns the mark: always confirm the compare value is a whole number and fits the timer's width. If f_clk ÷ (N × f_target) is not an integer, the period will be slightly off and the error accumulates over time.