8051 Tutorial 6: 8051 Interrupts Programming in C

Programming an Interrupt Driven Timer/Counter

If the 8051 Timer/Counter is still new to you, please read 8051 Tutorial 4: 8051 Timer/Counter Programming in C first.

1. Initialize the Timer/Counter first by loading the TMOD register by an appropriate value.

2. Load the THx and TLx with initial count values.

Read this to know how to initialize or set the mode of a timer/counter and to calculate the value to be loaded to THx and TLx.

3. Set the ET1 or ET0 bits of IE register to enable the interrupts of Timer 1 or Timer 0, respectively.

4. Enable the global interrupts by setting EA bit of the IE register.

5. Start the timer/s by setting TRx.

Example

Write a program that will generate a square wave with a period of 20ms on pin P3.0. Assume that the crystal frequency is 11.0592MHz.

Solution

#include<reg51.h>
sbit pulse = P3^0;
void toggle_pin(void) interrupt 3
{
 pulse = ~pulse;  //complement P3.0
}
void main(void)
{
  TMOD = 0b00010000; //Timer 1, mode 1 (16-bit)
  TL1=0x00;    // load TL with 0x00
  TH1=0xDC;    //load TH with 0xDC

  ET1=1;     //enable Timer 1 interrupt
  EA=1;      //enable global interrupt
  TR1=1;     //start Timer1
  while(1)   //loop forever
   {;}
}

You will notice in the code above that there is a subroutine associated to the interrupt of Timer 1. This is called the interrupt service routine or ISR. The routine inside the ISR is serviced every time an interrupt occurs.

You will also notice that the flag for the Timer is never monitored in software. This makes the programming easier to us and it minimizes the load of the MCU.

The flag of the Timer is automatically cleared by hardware after each time the ISR is serviced.

The interrupt of the Timer 1 points to the interrupt priority number 3. For Timer 1, the format of the ISR must be:

void your_ISR_name_here(void) interrupt 3
{
 //your routine here
}

The interrupt of the Timer 0 points to the interrupt priority number 1. For Timer 0, the format of the ISR must be:

void your_ISR_name_here(void) interrupt 1
{
 //your routine here
}

Pages: 1 2 3 4

Speak Your Mind

*