## Tapping the timer

Let’s now see how interrupts are handled in SDCC.

The microcontroller has three timers. The original firmware uses Timer 0
in order to implement the delay routine. It programs this timer to work
in Mode 1. In this mode, the TH0:TL0 registers contain a 16-bit counter
which is incremented every 12 ticks of the system clock running at
12MHz (in other words, each microsecond).

Note that if we used the full capability of the 16-bit timer counter and
used the timer interrupt as a completion signal, we could measure delays
of up to 6.5 milliseconds. This is way too short, so we resort to
counting interrupts. For convenience, we arrange it so that a timer
interrupt happens each millisecond while the timer is running.

The delay routine accepts as argument an 8-bit unsigned number of
milliseconds, stores in a variable, sets the timer count to −1000, and
enables the timer. After that, it waits until the delay count becomes 0.
Meanwhile, the timer interrupt service routine gets called whenever the
timer count overflows, decrements the delay count (if not already zero),
and resets the timer to −1000. (The hexadecimal for −1000 in two’s
complement code is `0xFC18`.)

The 8-bit size for the delay count means we are limited to delays of up
to 255 milliseconds, or roughly ¼s. For larger delays, we can call
`delay(250)` two, three or four times.

To illustrate that the timer works, we will blink the middle LED with a
period of 500 milliseconds.