Jan 21, 2017

How to program timer as timer in 8051 microcontroller.

Here we are using 89p51rd2 microcontroller for programming and 80c51 microcontroller for proteus simulation.
In this article we are programming for mode 1 timer 0. by changing TCON register you can change modes.
This program is to toggle port 1 of 8051.
Timer is used to provide delay to microcontroller.

  • In delay, firstly we define TMOD as 0x01, here timer 0 defined as timer mode 1.
  • We are providing 50ms delay through timer. so 50,000 machine cycles are required. (for  machine cycle 1us is required).
  • hence value to be loaded is 65535 - 50000 i.e. 15535. now we will convert 15535 into hex.
  • It comes as 0x3cb0. we will load higher 8 bits 0x3c in TH0 and lower 8 bits 0xb0 in TL0.
  • If previously overflow flag is 1 then it shall be reset to 0.
  • Now TR0 will start timer0.
  • Nextly we will wait for timer to overflow that is TF0 to become 1.
  • After that we will stop timer by setting TR0=0
We will repeat this 50ms delay for 20 times using for loop to obtain 1 second delay. 
This can be seen in the below code.

 #include<reg51.h>  
   
 void delay();  
   
 int main(void)  
 {  
      P1=0xf0;  
      while(1)  
      {  
           P1=~P1;  
           delay();  
      }  
 }  
   
 void delay()  
 {  
      unsigned char i;  
      for(i=0;i<20;i++)  
      {  
           //timer 0 mode 1  
           TMOD=0x01;  
             
           //load 15535 for 50ms delay  
           TH0=0x3c;  
           TL0=0xb0;  
             
           //reset overflow flag  
           TF0=0;  
             
           //start timer0   
           TR0=1;  
             
           //wait for overflow  
           while(TF0!=1);  
             
           //stop timer0  
           TR0=0;  
      }  
 }  

Program output:

Proteus simulation output:

Click on this link to download program and simulation files.

No comments:

Post a Comment