以下程序为89C52单片机的定时器T0,T1,T2定时1ms
第一份代码为三个定时器的初始化
#include <reg52.h>
void Timer0_Init()
{
TMOD &= 0xF0;
TMOD |= 0x01;
TH0 = 0xFC;
TL0 = 0x18;
TF0 = 0;
TR0 = 1;
EA = 1;
ET0 =1;
PT0 = 0;
}
void Timer1_Init()
{
TMOD &= 0x0F;
TMOD |= 0x10;
TH1 = 0xFC;
TL1 = 0x18;
TF1 = 0;
TR1 = 1;
EA = 1;
ET1 =1;
PT1 = 0;
}
void Timer2_Init()
{
RCAP2H = TH2 = 0xFC;
RCAP2L = TL2 = 0x18;
TF2 = 0;
TR2 = 1;
EA = 1;
ET2 =1;
PT2 = 0;
}
第二份代码为main.c 文件中使用定时器实现三个LED闪烁
#include <reg52.h>
#include "Timer.h"
sbit led1 = P0^1;
sbit led2 = P0^2;
sbit led3 = P0^3;
void main()
{
Timer0_Init();
Timer1_Init();
Timer2_Init();
while(1)
{
}
}
void Timer0_Routine() interrupt 1
{
static unsigned int T0count;
TH0 = 0xFC;
TL0 = 0x18;
T0count++;
if(T0count >= 1000)
{
T0count = 0;
led1 = ~led1;
}
}
void Timer1_Routine() interrupt 3
{
static unsigned int T1count;
TH1 = 0xFC;
TL1 = 0x18;
T1count++;
if(T1count >= 1000)
{
T1count = 0;
led2 = ~led2;
}
}
void Timer2_Routine() interrupt 5 using 1
{
static unsigned int T2count;
TF2 = 0;
T2count++;
if(T2count >= 1000)
{
T2count = 0;
led3 = ~led3;
}
}
|