SOFTWARE EXAMPLE

The software code contains all of the concepts discussed above. The timer/counter register itself, timer counter 0 (TCCNT0), is reloaded with the value 6 each time the ISR executes so that it can once again count up 250 steps to reach 255 and roll over. A global variable called “time_count” is used to keep track of the number of times that the interrupt service routine is executed by incrementing it each time the ISR is executed. “time_count” is both incremented and checked inside the expression of the if statement. When “time_count” reaches 250, the global variable is incremented and “time_count” is reset to zero to count up for the next 1 second period. With the 1`second time interval the real time clock can be made. In this program the real time clock is shown on a LCD display.

 

// program name: timer0_ovf_isr
// date: 2014.08.25
// target device: atmega8/atmega328p
// target: 1s interval
// author: www.avrprojects.net
// compiler: WINAVR GCC
// timero overflow interrupt service routine
// clk= 16MHz/256 = 62,500kHz = 16uS * 250 ticks = 4ms * 250 = 1s interval
#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(TIMER0_OVF_vect){//set timer to 256-250 = 6 TCNT0=6; ++time_count;if(time_count==250) {time_count=0;// set to 0 second++;// increase second if(second==60) {second=0; minute++; if(minute==60) {minute=0; hour++; if(hour==25) {hour=0; } } } }
} int main(void){

LCDini(); //set timer 0 prescaler to clk/256*/ TCCR0=0b00000100;// enable Timer 0 overflow interrupt*/ TIMSK=0x01;sei(); LCDgoto(0,0);LCDtxt("Interrupt timer0 OVF");
LCDgoto(0,1);LCDtxt(" Real Time Clock");
LCDgoto(0,3);LCDtxt("www.avrprojects.net"); while(1) { LCDgoto(6,2); if(hour<10) {LCDtxt("0"); LCDint(hour);} elseLCDint(hour); LCDtxt(":"); if(minute<10) {LCDtxt("0"); LCDint(minute);} elseLCDint(minute); LCDtxt(":"); if(second<10) {LCDtxt("0"); LCDint(second);} elseLCDint(second); }
}