52单片机定时器0-2实现1ms定时

以下程序为89C52单片机的定时器T0,T1,T2定时1ms

第一份代码为三个定时器的初始化

#include 

void Timer0_Init()     //定时器0方式一,配置1ms中断的函数
{
	TMOD &= 0xF0;
	TMOD |= 0x01;      //配置定时器0方式一,这样设置不影响定时器1的配置
//	TH0 = 64536/256;   //定时1ms,高8位(65536-1000)/256
//	TL0 = 64536%256;   //定时1ms,低8位(65536-1000)%256,这个不够精准,实际应该是(65536-1000)%256+1
	TH0 = 0xFC;
	TL0 = 0x18;
	TF0 = 0;		   //清除TF0标志
	TR0 = 1;		   //定时器0开始计时
	
	EA = 1;			   //开总中断
	ET0 =1;			   //开定时器0中断
	PT0 = 0;		   //中断优先级,0为低优先级,1为高优先级	
}

void Timer1_Init()     //定时器1方式一,配置1ms中断的函数
{
	TMOD &= 0x0F;
	TMOD |= 0x10;      //配置定时器0方式一,这样设置不影响定时器1的配置
	TH1 = 0xFC;
	TL1 = 0x18;
	TF1 = 0;		   //清除TF1中断标志
	TR1 = 1;		   //启动定时器1
	
	EA = 1;			   //开总中断
	ET1 =1;			   //开定时器1中断
	PT1 = 0;		   //中断优先级,0为低优先级,1为高优先级	
}

void Timer2_Init()     //定时器2,配置1ms中断的函数
{
	RCAP2H = TH2 = 0xFC; 
	RCAP2L = TL2 = 0x18; 
	TF2 = 0;		   //清除TF1中断标志
	TR2 = 1;		   //启动定时器1
	
	EA = 1;			   //开总中断
	ET2 =1;			   //开定时器1中断
	PT2 = 0;		   //中断优先级,0为低优先级,1为高优先级	
}

第二份代码为main.c文件中使用定时器实现三个LED闪烁

#include 
#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;
	}
}

你可能感兴趣的:(52单片机定时器0-2实现1ms定时)