Timers
In the Digital I/O section I provided some code to make an LED blink:
In this example, we used the __delay_ms() function to halt the CPU for a specified amount of time. This served our purposes well, but the CPU is unable to do anything useful during the delay. What if we wanted to make an LED blink once per second, but also perform other tasks at the same time? One solution is to use a Timer.
A timer is essentially a flexible counter. Each timer has a register that is incremented by a clock. When the register is incremented to the point that it rolls over (e.g. goes from 255 to 0 in an 8-bit timer), a status flag is set. If enabled, an interrupt will also occur.
Therefore the amount of time that passes in between timer interrupts is dependent on the speed of the clock feeding the timer and the starting value placed in the timer register.
The easiest way to understand how timers work is to look at some examples.
Example 1: Using a timer to wait a specific amount of time.
In this example we will mimic the functionality of the __delay_ms() function.