核心问题是动态扫描数码管没有消隐。
- #include "reg51.h"
- #include <intrins.h>
- #define uchar unsigned char
- #define uint unsigned int
- #define DIGIT_O P0//设置P0位数码管数据输出端
- //定义时分秒变量
- uchar timer,seconds,minutes,hours;
- uchar timer,seconds,minutes,hours = 0;
- //共阳极数字码表
- uchar code segCode[]={
- 0xc0,0xf9,0xa4,0xb0,
- 0x99,0x92,0x82,0xf8,
- 0x80,0x90,0x88,0x83,
- 0xc6,0xa1,0x86,0x8e};
- //定时器中断服务程序
- void timer0_ISR() interrupt 1
- {
- TH0 = 0xee; // 设置定时初值,一次中断为5ms
- TL0 = 0x00;
- timer++;
- if(timer==200) //到达1s
- {
- timer=0;
- seconds++;
- if (seconds == 60)
- {
- seconds = 0;
- minutes++;
- if (minutes == 60)
- {
- minutes = 0;
- hours++;
- if (hours == 24)
- {
- hours = 0;
- }
- }
- }
- }
- }
- void delay(uint x) //延时xms
- {
- uint i,j;
- for(i=x;i>0;i--)
- for(j=114;j>0;j--);
- }
- //初始化硬件
- void init()
- {
- TMOD = 0x01; // 定时器0工作在模式1(16位定时器)
- TH0 = 0xee; // 设置定时初值
- TL0 = 0x00;
- ET0 = 1; // 允许定时器0中断
- EA = 1; // 允许总中断
- TR0 = 1; // 启动定时器0
- seconds=0;
- minutes=0;
- hours=0;
- }
- // 显示时间
- void display_time()
- {
- static uchar data i;
- P3&=0xf0;//消隐
- switch(i)
- {
- case 0: DIGIT_O=segCode[minutes/10]; break;
- case 1: DIGIT_O=segCode[minutes%10]&0x7f; break;//加点
- case 2: DIGIT_O=segCode[seconds/10]; break;
- case 3: DIGIT_O=segCode[seconds%10]; break;
- }
- P3|=0x01<<i;
- i=++i%4;
- }
- void main()
- {
- init();
- while(1)
- {
- display_time();
- delay(1);
- }
- }
复制代码 |