代码如下(示例):
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
code uchar num[]=
{0xC0,0xF9,0x64,0x70,0x59,0x52,0x42,0xF8,0x40,0x50};
uchar oldkey=0xff;
void delay(uint i)
{
while(i--);
}
sbit SMG_0 = P1^3;
sbit SMG_1 = P1^2;
sbit SMG_2 = P1^4;
sbit SMG_3 = P1^1;
sbit led=P2^1;
sbit key1 = P3^7;
sbit key2 = P3^6;
sbit key3 = P3^5;
sbit key4 = P3^4;
uchar kk;
unsigned char ReadKey(void)
{
unsigned char lkey=0;
if((P3&0xfc)!=0xfc){
delay(10);
if(oldkey!=(P3&0xfc)){
oldkey=P3&0xfc;
if(key1==0)
lkey=1;
else if(key2==0)
lkey=2;
else if(key3==0)
lkey=3;
else if(key4==0)
lkey=4;
}
}
else{
oldkey=0xfc;
}
return lkey;
}
void display(uchar a,uchar b)
{
uchar aa=0,bb=0,cc=0,dd=0;
P0=0XFF;
SMG_0 = 1;
SMG_1 = 1;
SMG_2 = 1;
SMG_3 = 0;
aa=a%10;
P0=num[aa];
delay(250);
SMG_0 = 1;
SMG_1 = 1;
SMG_2 = 0;
SMG_3 = 1;
bb=a/10;
P0=num[bb];
delay(250);
SMG_0 = 1;
SMG_1 = 0;
SMG_2 = 1;
SMG_3 = 1;
cc=b%10;
P0=num[cc];
delay(250);
SMG_0 = 0;
SMG_1 = 1;
SMG_2 = 1;
SMG_3 = 1;
dd=b/10;
P0=num[dd];
delay(250);
}
void main()
{
uchar ms=59;
uchar min=59;
uchar hour=23;
TMOD=0x01;
TH0=(65536-10000)/256;
TL0=(65535-10000)%256;
EA=1;
ET0=1;
TR0=1;
while(1)
{
switch(ReadKey()){
case 1:min++;
break;
case 2:min--;
break;
case 3:hour++;
break;
case 4:hour--;
break;
}
if(min>59)
{
min=0;
hour++;
}
if(hour>23)
{
hour=0;
min=0;
}
if(kk==100)
{
kk=0;
led=!led;
ms++;
if(ms>60)
{
ms=0;
min++;
if(min>59)
{
min=0;
hour++;
}
}
}
display(min,hour);
}
}
void timer0() interrupt 1
{
TH0=(65536-10000)/256;
TL0=(65535-10000)%256;
kk++;
}