|
刚刚做的一个计时器的练习,供你参考。
- /*
- 题目:采用定时器中断进行每隔一秒计数
- 时间:2009-11-28
- 作者:wbx
- 简述:
- (1)设置定时器工作模式为0x01为16位定时器模式 TMOD = 0x01;
- (2)开总中断EA使其为1
- (3)设置TH0、TL0的内容,填充数值到其中
- (3)开总中断EA = 1;
- (4)设置ET0 = 1;打开定时器中断
- (5)TR0 = 1; 启动定时器0
- (6)进行计数,且将第一个LED进行显示
- */
- #include
- code unsigned char tab[]=
- {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
- unsigned int n = 0;
- unsigned int count = 0;
- unsigned char showLed = 0xff;
- void delay(unsigned int iTime)
- {
- while(--iTime);
- }
- //定时器中断函数
- void TimerFunction() interrupt 1
- {
- TH0 = (65535 - 50000) / 256;
- TL0 = (65535 - 50000) % 256;
- n++;
- }
- void InitTimer()
- {
- //定时器中断的一些初始化参数
- TMOD = 0x01;
- TH0 = (65535 - 50000) / 256;
- TL0 = (65535 - 50000) % 256;
- EA = 1;
- ET0 = 1;
- TR0 = 1;
- }
- //数码管显示计数函数
- void ShowCount()
- {
- //百位
- P0 = tab[count/100];
- P2 = 0;
- delay(800);
- //十位
- P0 = tab[(count - (count/100)*100 )/10];
- P2 = 1;
- delay(800);
-
- //个位
- P0 = tab[(count - (count/100)*100 )%10];
- P2 = 2;
- delay(800);
- }
- void main()
- {
- InitTimer();//初始化定时器
- while(1)
- {
- ShowCount();//采用数码管进行显示
- if (n>=20) //如果达到 20*50000(计数器设置的初始值)=1000000微妙=1秒则进行处理如下代码
- {
- if (showLed == 0xfe )
- showLed = 0xff;
- else
- showLed = 0xfe;
-
- P1 = showLed;
- n = 0;
- count++;
- }
- if (count>=999) count = 0;
- }
- }
复制代码 |
|