TIMER 0

Timer 0 is a 8 bit timer/counter, it is most often used as a time base or a tick for the program. Timer counter control register 0 (TCCR0), controls the function of Timer 0 by selecting the clock source applied to Timer 0. A program tick, like the tick of a clock, provides a highly accurate timing event. The overall scheme is that a number is selected and loaded into the timer. The timer counts from this number up to 255 and rolls over. Whenever it rolls over, it generates an interrupt. The interrupt service routine reloads the same number into the timer, executes any time-critical activities that may be required, and then returns to the program. The cycle then repeats, with the counter counting up from the number that was loaded to 255, and rolls over, generating another interrupt. The interrupt, then, is occurring on a regular basis when each time period has elapsed. The number loaded into the counter determines the length of the period. The lower the number, the longer it will take the timer to reach to 255 and roll over, and the longer the period of the tick will be.

As an example we will generate a 1 second tick as a time base for a real time clock.

For a timer to be used as a tick, the first necessary task is to determine the number that is loaded into the timer each time the interrupt occurs. We want the program to generate a tick every second. In this program we use a 16MHz clock and we set the prescaler to clk/256.

16/MHz/256 = 62.500 KHz = 16µs

This shows that every 16µs another clock pulse will be applied to Timer 0. Timer 0 is an 8-bit timer/counter, and so it can count up to 256 such periods before it rolls over. By using 250 coount this will give a time period of:

250 x 16µs = 4ms

Therefore, the counter reload number would be as follows:

256 x 250 = 6

This means that the interrupt service routine (ISR) will be executed once every 4 milliseconds. A global variable will be used to count to 250 to produce the entire 1 second time period:

4ms x 250 = 1s