#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uchar dd[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf};
//数码管断码表
uchar shi=9,fen=59,miao=55; //时间初始值
uchar shi1=10,fen1=5,miao1=0;//闹钟初始值
uchar yi,er,san,si,wu,liu,qi,ba;
uchar count=0;//计数变量
sbit led=P1^0; //LED端口
sbit buzz=P1^1;//蜂鸣器
sbit k1=P1^2; //模式切换
sbit k2=P1^3; //加
sbit k3=P1^4; //减
sbit k4=P1^5; //时间 时分秒切换
sbit k5=P1^6; //闹钟 时分秒切换
bit k1_flag=0;
uchar k4_flag=0,k5_flag=0;
void delay1ms() //@11.0592MHz
{
unsigned char i, j;
_nop_();
_nop_();
_nop_();
i = 11;
j = 190;
do
{
while (--j);
} while (--i);
}
//数码管显示时间
void display(uchar yi,uchar er,uchar san,uchar si,uchar wu,uchar liu,uchar qi,uchar ba)
{
P3=0x01; //位选
P2=dd[yi]; //段选
delay1ms();
P3=0x02;
P2=dd[er];
delay1ms();
P3=0x04; //位选
P2=dd[san]; //段选
delay1ms();
P3=0x08;
P2=dd[si];
delay1ms();
P3=0x10; //位选
P2=dd[wu]; //段选
delay1ms();
P3=0x20;
P2=dd[liu];
delay1ms();
P3=0x40; //位选
P2=dd[qi]; //段选
delay1ms();
P3=0x80;
P2=dd[ba];
delay1ms();
}
void keys()
{
if(k1==0)
{
delay1ms();
if(k1==0) //
{
k1_flag=~k1_flag;
if(k1_flag==0)
{ET0=1;}
}while(k1==0);
}
if(k2==0)
{
delay1ms();
if(k2==0) //
{
if(k4_flag==1)
{shi++;if(shi==24){shi=0;}}
if(k4_flag==2)
{fen++;if(fen==60){fen=0;}}
if(k4_flag==3)
{miao++;if(miao==60){miao=0;}}
if(k5_flag==1)
{shi1++;if(shi1==24){shi1=0;}}
if(k5_flag==2)
{fen1++;if(fen1==60){fen1=0;}}
if(k5_flag==3)
{miao1++;if(miao1==60){miao1=0;}}
}while(k2==0);
}
if(k3==0)
{
delay1ms();
if(k3==0) //
{
if(k4_flag==1)
{shi--;if(shi==-1){shi=23;}}
if(k4_flag==2)
{fen--;if(fen==-1){fen=59;}}
if(k4_flag==3)
{miao--;if(miao==-1){miao=59;}}
if(k5_flag==1)
{shi1--;if(shi1==-1){shi1=23;}}
if(k5_flag==2)
{fen1--;if(fen1==-1){fen1=59;}}
if(k5_flag==3)
{miao1--;if(miao1==-1){miao1=59;}}
}while(k3==0);
}
if(k4==0)
{
delay1ms();
if(k4==0) //
{
ET0=0;
if(k1_flag==0)
{
k4_flag++;
if(k4_flag==4)
{ET0=1;k4_flag=0;}
}
}while(k4==0);
}
if(k5==0)
{
delay1ms();
if(k5==0) //
{
ET0=0;
if(k1_flag==1)
{
k5_flag++;
if(k5_flag==4)
{k5_flag=0;}
}
}while(k5==0);
}
}
void Timer0Init(void) //100微秒@11.0592MHz
{
TMOD = 0x01; //设置定时器模式
TL0 =(65536-50000)%256; //设置定时初值
TH0 =(65536-50000)/256; //设置定时初值
TF0 = 1; //清除TF0标志
TR0 = 1; //定时器0开始计时
EA=1;
ET0=1;
}
void serviceTimer0Init() interrupt 1
{
TL0 =(65536-50000)%256; //设置定时初值
TH0 =(65536-50000)/256;
count++;
if(count==20) //20*50000=1秒
{
count=0;
miao++;
}
if(miao==60) //
{
miao=0;fen++;
}
if(fen==60) //
{
fen=0;shi++;
}
if(shi==24)
{shi=0;}
if((shi==shi1)&&(fen==fen1)&&(miao==miao1))
{
led=~led;buzz=0;
}
else
{
buzz=1;led=0;
}
}
//主函数
void main()
{
yi=1,er=2,san=3,si=4,
wu=5,liu=6,qi=7,ba=8;
Timer0Init();
led=0;buzz=1;
while(1)
{
if(k1_flag==0)
{
yi=shi/10,er=shi%10,san=10,si=fen/10,
wu=fen%10,liu=10,qi=miao/10,ba=miao%10;
}
else if(k1_flag==1)
{
yi=shi1/10,er=shi1%10,san=10,si=fen1/10,
wu=fen1%10,liu=10,qi=miao1/10,ba=miao1%10;
}
keys();
display(yi,er,san,si,wu,liu,qi,ba);
}
}