此程序是在51hei单片机开发板上面做的,如需要移植到自己的电路上,修改相应的端口即可,开发板完整的电路图下载: 点这里 (注意:只需要看相关部分即可,其他部分可以忽略)
//****80c52***时钟程序
//***手把手教你学单片开发板***
//**2012/9/7***23:02***
# include<reg52.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
typedef unsigned long uint32;
uint8 block[]={0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90};//显示数组
uint8 a[6];
uint16 counter=0;
uint32 sec=0;
#define tr 40 //发声值
bit MS = 1; //状态字;
sbit ADDR0 = P1^0; //A0****
sbit ADDR1 = P1^1; //A1*****
sbit ADDR2 = P1^2; //A2*****
sbit ADDR3 = P1^3; //E1|E2**
sbit ENLED = P1^4; //E3****38译码器
sbit BUZZ = P1^6; //蜂鸣器
sbit keyout1 = P2^3; //按键公共端
sbit keyin1 = P2^4; //k1 长安0.1S进入时间调节;
sbit keyin2 = P2^5; //k2 时间调节断码选择
sbit keyin3 = P2^6; //k3 调节时间加
sbit keyin4 = P2^7; //k4 调节时间减
void refresh_LS(); //数码管扫描函数
void timer1_int(); //定时器1中断函数
void keying(); //按键读取函数
void display(); //数码管显示函数
void buzzer(); //蜂鸣器发声函数
void delay(uint16 n); //延时函数
main()
{
keyout1 = 0;
keyin1 = 1; keyin2 = 1; keyin3 = 1; keyin4 = 1;
ENLED = 0; ADDR3 = 1;
timer1_int();
display();
while(1)
{
if(keyin1 == 0)
{
delay(100000);
if(keyin1 == 0)
{
MS = ~MS;
buzzer();
while(!keyin1);
}
}
if(MS == 0)keying();
}
}
void buzzer()
{
static uint8 i=0;
for(i=0;i<tr;i++)
{
BUZZ =~BUZZ;
delay(100);
}
BUZZ = 1;
}
void delay(uint16 n)
{
while(n--);
}
void timer1_int()
{
TMOD |= 0X10;
TMOD &= 0xdf;
TH1 = 0xfc;
TL1 = 0x67;
TR1 = 1;
EA = 1;
ET1 = 1;
}
void interrupt_tiner1() interrupt 3
{
TH1 = 0xfc;
TL1 = 0x67;
counter++;
if(counter == 1000)
display();
refresh_LS();
}
void display()
{
counter = 0;
if(sec>=86400)sec=0;
a[0] = 0x7f&block[sec%10];
a[1] = block[sec/10%6];
a[2] = 0x7f&block[sec/60%10];
a[3] = block[sec/600%6];
a[4] = 0x7f&block[sec/3600%10];
a[5] = block[sec/36000%3];
if(MS ==1)sec++;
}
void keying()
{
static uint8 i=0,y,y1;
if(keyin2 == 0)
{
i+=2;
if(i == 6)i=0;
delay(500);
}
else if(keyin3 == 0)
{
if(i == 0)sec++;
else
if(i == 2)sec+=60;
else
if(i == 4)sec+=3600;
delay(1000);
}
else if(keyin4 == 0)
{
if(i == 0)sec--;
else
if(i == 2)sec-=60;
else
if(i == 4)sec-=3600;
delay(500);
}
display();
if((keyin1 == 0)||(keyin2 == 0)||(keyin3 == 0)||(keyin4 == 0))buzzer();
while((keyin1 == 0)||(keyin2 == 0)||(keyin3 == 0)||(keyin4 == 0));
y = a[i];
y1 = a[i+1];
a[i] = 0xff;
a[i+1]=0xff;
delay(5000);
a[i] = y;
a[i+1]=y1;
delay(5000);
}
void refresh_LS()
{
static uint8 j=0;
switch(j)
{
case 0: ADDR0 = 0; ADDR1 = 0; ADDR2 = 0; P0=a[0]; j++; break;
case 1: ADDR0 = 1; ADDR1 = 0; ADDR2 = 0; P0=a[1]; j++; break;
case 2: ADDR0 = 0; ADDR1 = 1; ADDR2 = 0; P0=a[2]; j++; break;
case 3: ADDR0 = 1; ADDR1 = 1; ADDR2 = 0; P0=a[3]; j++; break;
case 4: ADDR0 = 0; ADDR1 = 0; ADDR2 = 1; P0=a[4]; j++; break;
case 5: ADDR0 = 1; ADDR1 = 0; ADDR2 = 1; P0=a[5]; j=0; break;
default: break;
}
}