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 hte 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 in 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). 

 


 

Program Example

Lets take this into practice and connect a 32,768 kHz crystal to the XTAL1 and XTAL2. On PORT B we connect a 16x2 LCD display for the result. See the circuit diagram below.


 

 Software Code

Now we make the program code that shows thereal  time on the LCD display. We use the external crystal as the source for the asynchronous clock. The asyncronous clock is the time base for the real time clock. It will overflow TIMER2 128 times each second. The overflow will generate a interrupt that makes the program jump the the Interrupt Service Routine (ISR). In the ISR a counter counts to 128, when it reaches 128 it will increase the seconds counter. The seconds will be converted into minutes and hours.

// program name: timer2 asynchronous timer
// date: 2015.08.25
// target device: atmega8/atmega328p
// target: 1s interval for RTC
// author: www.avrprojects.net
// compiler: AVR_GCC
// timer2 overflow interrupt service routine
#include <avr/io.h>
#include <util/delay.h>
#include <util/lcd.h>
#include <avr/interrupt.h>
unsigned char time_count; int second=0; int minute=19; int hour=11;

/// Timer 0 overflow interrupt service routine
ISR(TIMER2_OVF_vect)
{
TCNT2 = 0;//set timer second++;// increase second } int main void)
{
LCDini(); TIMSK=0;//disable timer2 interrupts ASSR=0b00001000;//set timer2 to asynchronous mode TCNT2=0;
TCCR2=0b0000101;// set prescaler to 1/128 while (ASSR&((1<<TCN2UB)|(1<<TCR2UB)));//wait for registers update TIFR=0b01000000;//clear interrupt flags TIMSK=0b01000000;// enable Timer2 overflow interrupt sei();// enable global interrupts LCDgoto(0,0);
LCDtxt(" TIMER2 Clock ");
charmystr[4]="";// save enough space for result itoa(second,mystr,10);// convert to ascii LCDgoto(0,1);
LCDtxt(mystr);// display in on LCD while(1) { }
}