Timer Overflow Interrupts  
As we saw in Introduction to Interrupts that Timer0 and Timer1 both can be used as an interrupt source lets see how???

Since at any particular time Timer registers TH0,TL0 can hold some contant value. On up counting values in these register increases by one in each machine cycle. As it is a total of 16 bit register, it can hold maximum value of 65535. So when timer make counting and reaches to top that is 65535; timer get overflow. Mean to say timer then start from 0 count. When timer overflows a Timer Flag bit TF0/TF1 is asserted by Timer block. Which can be used to interrupt the CPU. It is known as Timer Overflow Interrupt.

Now suppose we have a task of generating a LED toggle period of 1Sec and simultanously we need to scan the switch; when switch is pressed toggle another LED.

So we are now performing two tasks simultanously; one is to toggle an LED with a precise delay of 1 sec and at same time scan the switch. whenever user pushes the switch toggle another LED which is initially OFF.





/*****************************************************************
Example to demonstrate Timer Overflow Interrupt.

Using Timer Mode 2 that is 8 bit auto reload. TMOD=0x02;

If we generate a total of 10uSec delay in one interrupt. We need 10000 interrupts to generate a delay of one second.

Total machine cycles required to generate 10usec delay = 9

TH0 fixed value will be 0xFF-0x09 = 0xF6;

Using TH0= 0xF6; an overflow interrupt will generate after each 9 counts.

*****************************************************************/

#include<at89x52.h>
sbit switch = P2^0;
sbit LED = P1^3; // Will lit up only when PB2 is pressed
sbit LED1 = P1^0; // To get toggle every second


volatile unsigned int wait=0;

void timer0(void) interrupt 1
{
wait++;
if(wait>10000) // check if one second is elapsed
{
LED1=~LED1;
wait=0;
}
}

void main(void)
{
switch=1; // P2_0 as input
TMOD=0x02; // Timer0 Mode 2 -> 8 bit auto reload
TH0=0xF6; // Each interrupt generate after a 10msec intervel.
IE=0x82; // Timer0 Overflow Interrupt Enable
TR0=1; // Timer0 ON while(1)
{
if(switch==0)
{
LED=0; // Lit LED
}
else
{
LED=1; // LED Off
} }
}



In the above code examples Switch is scanned by polling while LED1 is toggled with a delay of 1 second using Interrupt. So both the process run at almost same time.
Timer1 overflow interrupt is also used in exact similar way.


Now try to learn External Interrupts on your own; read datasheet of AT89S52 carefully and implement code. If you face any problem in External Interrupts mail me your query. :-)

devesh@electroons.com
Best viewed at Firefox 1024x768 resolution