Using the TIMER/COUNTER 2

TIMER2 is a 8-bit Timer with PWM and output compare functions like TIMER1. The most interesting feature of TIMER2 it that it can use a external crystal separate from the system clock and the clock source.

Using a external crystal allows TIMER2 to function as the time base for a real-time clock. The external X-tal can be selected by setting the AS2 bit in the asynchronous status register (ASSR). Setting TIMER2 to use the external clock source means that it is running asynchronously to the system clock. The other 3 bits in the ASSR register are used the ensure that the data is not written into the TIMER2 register at the same moment that the hardware is updating the TIMER2 registers, because the oscillator of Timer 2 is asynchronous to the system oscillator, and it is possible to corrupt the data in the Timer 2 registers by writing data to the registers as they attempt to update.

The Timer Control Regsiter 2 (TCCR2), controls the operation of Timer 2.

Using a 32.768 kHz crystal as a clock source for TIMER2 allows the microcontroller to keep accurat time. The 32.768 kHz crystal will overflow TIMER2 exactly 128 times each second. (256 * 128 =32768). By setting the presclaer to 128 each time the timer overflows is exactly 1 second. So there you have the time base for a clock.