Interrupts & Programming 8051 Hardware Interrupts


1. Programming Timer Interrupts
The timer interrupts IT0 and IT1 are related to Timers 0 and 1, respectively. (Please refer 8051 Timers for details on Timer registers and modes.) The interrupt programming for timers involves following steps :
 
1.                  Configure TMOD register to select timer(s) and its/their mode.
2.                  Load initial values in THx and TLx for mode 0 and 1; or in THx only for mode 2.
3.                  Enable Timer Interrupt by configuring bits of IE register.
4.                  Start timer by setting timer run bit TRx.
5.                  Write subroutine for Timer Interrupt. The interrupt number is 1 for Timer0 and 3 for Timer1.
       Note that it is not required to clear timer flag TFx.
6.                 To stop the timer, clear TRx in the end of subroutine. Otherwise it will restart from 0000H in case of modes 0 or 1 and from initial values in case of mode 2.
7.                 If the Timer has to run again and again, it is required to reload initial values within the routine itself (in case of mode 0 and 1). Otherwise after one cycle timer will start counting from 0000H.
 
Example code
Timer interrupt to blink an LED; Time delay in mode1 using interrupt method
// Use of Timer mode0 for blinking LED using interrupt method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit LED = P1^0; //LED connected to D0 of port 1

void timer(void) interrupt 1 //interrupt no. 1 for Timer 0
{
led=~led; //toggle LED on interrupt
TH0=0xFC; // initial values loaded to timer
TL0=0x66;
}
main()
{
TMOD = 0x01; // mode1 of Timer0
TH0 = 0xFC; // initial values loaded to timer
TL0 = 0x66;
IE = 0x82; // enable interrupt
TR0 = 1; //start timer
while(1); // do nothing
}
 
You are here