51单片机实验2017年12月4日

2017年12月4日

定时器LED延时程序

#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char     //宏定义名称替换函数
uchar count;                     //无符号字符型函数
sbit LED1 = P1^0;                   //打开LED端口 

void main()                      //主函数开始
{
	TMOD = 0x01;                //定时器0/计数器0工作方式0模式1
	TH0 = (65536-45872)/256;         //高八位重装值
	TL0 = (65536-45872)%256;            //低八位重装值
//重装值计算在前面有写过,它就是用来定count加一次隔多长时间的
	TR0 = 1;                          //启动定时器0
	ET0 = 1;                            //开定时器0的中断
	EA  = 1;                          //开总中断
	while(1);                         //等待中断,即当中断服务程序开始到满一秒计数之前
                                           //main函数中的中断程序一直在运行直到计数满一秒
}

void T0_time() interrupt 1                           //定时器中断服务程序开始
{
		TH0 = (65536-45872)/256;            //高八位重装值
		TL0 = (65536-45872)%256;             //低八位重装值
		count ++;                          //count 自加1,1次50毫秒
		if(count == 20)                    //测试count是否加了20次,即是否满1000ms=1s
		{
			count = 0;                  //count清零
			LED1 = ~LED1;                  //LED灯取反,单片机输出低电平点亮LED灯,程序从头开始
		}
}

猜你喜欢

转载自blog.csdn.net/a1995_1995/article/details/78714234