What is a Timer
8051 Timer Issues
Fig. 2: Image showing Status of Timer Flag on Roll Over
Starting or stopping a Timer
Fig. 3: Bit Values of TMOD Register of 8051 Microcontroller
The lower four bits (TMOD.0 – TMOD.3) are used to configure Timer 0 while the higher four bits (TMOD.4 – TMOD.7) are for Timer 1. When GATE is high, the corresponding Timer is enabled only when there is an interrupt at corresponding INTx pin of AT89C51 controller and Timer control bit is high. Otherwise only setting Timer control bit is sufficient to start the Timer.
void ISR_Timer0(void) interrupt 1
{
<Body of ISR>
}
ISR definition for Timer 1 :
void ISR_Timer1(void) interrupt 3
{
<Body of ISR>
}
6. If the Timer has to be stopped after once the interrupt has occurred, the ISR must contain the statement to stop the Timer.
void ISR_Timer1(void) interrupt 3
{
<Body of ISR>
TR1 =0;
}
void ISR_Timer1(void) interrupt 3
{
<Body of ISR>
TH1 =0XFF; //load with initial values if in mode 0 or 1
TL1 = 0xFC;
}
Different modes of a Timer
Mode
|
M1
|
M0
|
Operation
|
Mode 0
|
0
|
0
|
13-bit Timer
|
Mode 1
|
0
|
1
|
16-bit Timer
|
Mode 2
|
1
|
0
|
8-bit Auto Reload
|
Mode 3
|
1
|
1
|
Split Timer Mode
|
Time delay in Mode1 using polling method
// Use of Timer mode 1 for blinking LED using polling method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit led = P1^0; // LED connected to 1st pin of port P1
void delay();
main()
{
unsigned int i;
while(1)
{
led=~led; // Toggle LED
for(i=0;i<1000;i++)
delay(); // Call delay
}
}
void delay() // Delay generation using Timer 0 mode 1
{
TMOD = 0x01; // Mode1 of Timer0
TH0= 0xFC; // FC66 evaluated hex value for 1millisecond delay
TL0 = 0x66;
TR0 = 1; // Start Timer
while(TF0 == 0); // Using polling method
TR0 = 0; // Stop Timer
TF0 = 0; // Clear flag
}
Time delay in Mode1 using interrupt method
// Use of Timer mode 1 for blinking LED with interrupt method // XTAL frequency 11.0592MHz #include<reg51.h> sbit LED = P1^0; // LED connected to 1st pin of port P1 void Timer(void) interrupt 1 // Interrupt No.1 for Timer 0 { led=~led; // Toggle LED on interrupt } main() { TMOD = 0x01; // Mode1 of Timer0 TH0=0x00; // Initial values loaded to Timer TL0=0x00; IE = 0x82; // Enable interrupt TR0=1; // Start Timer while(1); // Do nothing }
// Use of Timer mode 2 for blinking LED with polling method // XTAL frequency 11.0592MHz #include<reg51.h> sbit led = P1^0; // LED connected to 1st pin of port P1void delay(); main() { unsigned int i; while(1) { led=~led; // Toggle LED for(i=0;i<1000;i++) delay(); // Call delay } } void delay() { TMOD = 0x02; // Mode1 of Timer0 TH0= 0xA2; // Initial value loaded to Timer TR0 = 1; // Start Timer while(TF0 == 0); // Polling for flag bit TR0 = 0; // Stop Timer TF0 = 0; // Clear flag }
(iv) Mode 3 : Split Timer
Filed Under: Tutorials
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.