自己做的一个电子钟
数码管是共阴的#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit duan=P2^6;
sbit wei=P2^7;
sbit key1=P3^7; //进入时钟
sbit key2=P3^6; //位选
sbit key3=P3^5; //段选
uchar code bianma[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uchar code bianmaw[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf};
uchar p,q,shi,ge,shi1,ge1,shi2,ge2,ss=0,mm=0,hh=0,z=0,zz=0,s1,m1,h1;
uint i,j,p1=0,p2=0,p3=0;
void delay(q)
{
for(i=100;i>0;i--)
for(j=q;j>0;j--);
}
void first() //初始化函数
{
ss=shi*10+ge;
mm=shi1*10+ge1;
hh=shi2*10+ge2;
s1=ss,m1=mm,h1=hh;
shi=ss/10,ge=ss%10;
shi1=mm/10,ge1=mm%10;
shi2=hh/10,ge2=hh%10;
IE=0x82; //允许定时器0中断
TMOD=0x01; //选定时器为工作方式1
TH0=(65536-50000)/256; //装初值
TL0=(65536-50000)%256;
TR0=1 //开始计时
}
void keyo()
{
key1=1;
do
{
P0=0x00;
duan=1;
P0=bianma[zz];
switch(z)
{
case 0:if(zz>2)zz=0;shi2=zz;break;
case 1:ge2=zz;if(zz>3)zz=0;break;
case 2:if(zz>5)zz=0;shi1=zz;break;
case 3:ge1=zz;break;
case 4:if(zz>5)zz=0;shi=zz;break;
case 5:ge=zz;break;
}
duan=0;
P0=0xff;
wei=1;
P0=bianmaw[z];
wei=0;
while(!key2);
delay(8);
if(!key2)
{
z++;
if(z>5)
z=0;
}
if(!key3)
{
delay(100);
if(!key3)
{
zz++;
if(zz>9)
zz=0;
}
}
}
while(key1);
}
void main()
{
keyo();
first();
while(1)
{
{
P0=0x00;
duan=1;
P0=0x80;
duan=0;
P0=0xff;
wei=1;
P0=0xf5;
wei=0;
delay(1);
if(p==20)
{ p=0;
ss++; //注意这两句位置换不得,否则要搓开1秒
shi=ss/10,ge=ss%10;
}
if(p1==60-s1)
{
s1=0;
p1=0;
ss=0;
mm++;
shi1=mm/10;
ge1=mm%10;
shi=ss/10,ge=ss%10;
}
if(p2==60-m1)
{
m1=0;
p1=0;
p2=0;
ss=0;
mm=0;
hh++;
shi=ss/10;
ge=ss%10;
shi1=mm/10,ge1=mm%10;
shi2=hh/10,ge2=hh%10;
}
if(p3==24-h1)
{
h1=0;
p=0,p1=0,p2=0,p3=0;
ss=0,mm=0,hh=0;
shi=ss/10, ge=ss%10;
shi1=mm/10,ge1=mm%10;
shi2=hh/10,ge2=hh%10;
}
duan=1;
P0=bianma[shi];
duan=0;
wei=1;
P0=0xef; //秒针
wei=0;
delay(1);
duan=1;
P0=bianma[ge];
duan=0;
wei=1;
P0=0xdf; //秒针
wei=0;
delay(1);
duan=1;
P0=bianma[shi1];
duan=0;
wei=1;
P0=0xfb; //分针十位
wei=0;
delay(1);
duan=1;
P0=bianma[ge1]; //分针个位
duan=0;
wei=1;
P0=0xf7;
wei=0;
delay(1);
duan=1;
P0=bianma[ge2];
duan=0;
wei=1;
P0=0xfd; //时针十位
wei=0;
delay(1);
duan=1;
P0=bianma[shi2]; //时针个位
duan=0;
wei=1;
P0=0xfe;
wei=0;
delay(1);
}
}
}
void int0() interrupt 1 //定时器0中断函数
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
p++;
if(p==20)
p1++;
if(p1==60-s1)
p2++;
if(p2==60-m1)
p3++;
}