Thursday, 10 January 2013

8051(AT89C51) Timer0 and Timer1 Code + Proteus simulation

Note: the idea of this post comes from this post(8051(AT89C51) timer0 code + Proteus simulation) and (8051(AT89C51) timer1 code + Proteus simulation). Thank  Saeed, he wrote some great tutorials. And from his blog, I first know the software Proteus. This post contains something that Saeed didn't mention in his  blogs. As a beginner, I think the most important thing is understanding the environment and testing the code in person. After that, you can try to combine Timer0 and Timer1 by yourself.

Environment:
IDE: Keil µVision4
The interface of Keil is this:

When you build your project, you need to generate the .hex file. This could be done by following steps
1.right click Target1>Options for Target "Target 1"
2.select Tab Output > select create HEX File


Simulation Software: Proteus 7.7(the newest version is 7.10)
To make the simulation work, here I only use 4 components. The following figure shows the simulation

Component 1: Terminals Mode->POWER
Component 2: Component Mode->P->AT89C52
Component 3: Virtual Instrument Mode-> OSCILLOSCOPE
Component 4: After you run this simulation -> Debug (Menu)

Now you need to load you .hex file to the microcontroller. Double Click the Component AT89C52, you will get a figure likes this:
Load the file via the Program File item(purple)

Here is the Source code:


#include<reg51.h>

// Out Pin
sbit Out0 = P0^0;     // Pin P0.0 is named as Out0, for timer0
sbit Out1 = P0^1;    // Pin P0.1 is named as Out1, for timer1

//Function declarations
void initPort(void);
void initTimer(void);


int main(void)
{
   initPort();             //initialize port
   initTimer();           // initialize Timer

   while(1)                // Reset is done in Timer interrupt
   {
   }
}

void initPort(void)    // Make all ports zero
{
 P0 = 0x00;   
 P1 = 0x00;   
 P2 = 0x00;   
 P3 = 0x00;  
}


void initTimer(void)
{
 TMOD &= 0xFF;    // Clear 4bit field for timer1
 TMOD |= 0x22;    // Set timer1 in mode 2,8-bit autoload mode
 
 
 TH0 = 0x05;    
 TL0 = 0x05;
 TH1 = 0x05;      // 250 usec reloading time
 TL1 = 0x05;      // First time value
 
 ET0 = 1;     //Enable Timer0 interrupt
 ET1 = 1;         // Enable Timer1 interrupt
 EA  = 1;         // Global interrupt enable
 
 TR0 = 1;     //start timer 0
 TR1 = 1;         // Start Timer 1
}


void Timer0_ISR (void) interrupt 1         //this function is invoked every 85usec
{
 Out0 = ~Out0; 
 TF0 = 0;     //clear the interrupt flag for timer 0
}

void Timer1_ISR (void) interrupt 3   // It is called every 250usec, has higer priority
{
 Out1 = ~Out1;  // Toggle Out pin

 TF1 = 0;     // Clear the interrupt flag
}

No comments:

Post a Comment