#include<reg52.h> sbit ADDR0 = P1^0; sbit ADDR1 = P1^1; sbit ADDR2 = P1^2; sbit ADDR3 = P1^3; sbit ENLED = P1^4; sbit ENLCD = P1^5; sbit KeyIn2 = P2^5; sbit KeyIn3 = P2^6; sbit BUZZ = P1^6; unsigned char LED[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90}; void main() { bit buff=1;//buf为KeyIn2上一次状态 bit bufff=1;//buf为KeyIn3上一次状态 unsigned int i,tt; static char bit_p[6]={0,0,0,0,0,0}; static int cnt,sec,min,hour; i = 0; sec=0; min=0; hour=0; ENLED = 0; ENLCD = 0; ADDR3 = 1; TMOD = 0x10; TH1 = 0xFC; TL1 = 0x66; TR1 = 1; P2 = 0xFE; while(1) { if(TF1==1) { TF1 = 0; TH1 = 0xFC; TL1 = 0x66; cnt++; if(cnt ==1000) { cnt = 0; //秒 sec++; bit_p[0]=sec%10; bit_p[1]=sec/10%10; if(sec==60) { sec=0; //分钟 min++; bit_p[2]=min%10; bit_p[3]=min/10%10; } if(min==60) { min=0; //小时 hour++; bit_p[4]=hour%10; bit_p[5]=hour/10%10; } } switch (i) { case 0:ADDR2 = 0;ADDR1 = 0;ADDR0 = 0;P0 = LED[bit_p[0]];i++;break; case 1:ADDR2 = 0;ADDR1 = 0;ADDR0 = 1;P0 = LED[bit_p[1]];i++;break; case 2:ADDR2 = 0;ADDR1 = 1;ADDR0 = 0;P0 = LED[bit_p[2]];i++;break; case 3:ADDR2 = 0;ADDR1 = 1;ADDR0 = 1;P0 = LED[bit_p[3]];i++;break; case 4:ADDR2 = 1;ADDR1 = 0;ADDR0 = 0;P0 = LED[bit_p[4]];i++;break; case 5:ADDR2 = 1;ADDR1 = 0;ADDR0 = 1;P0 = LED[bit_p[5]];i=0;break; } } //设置时钟的分钟 if(KeyIn2!=buff) { if(buff==0) { TR1=0; min--; if(min==-1) { min=60; } bit_p[2]=min%10; bit_p[3]=min/10%10; } buff=KeyIn2; TR1=1; } //设置时钟的小时 if(KeyIn3!=bufff) { if(bufff==0) { TR1=0; hour--; if(hour==-1) { hour=24; } bit_p[4]=hour%10; bit_p[5]=hour/10%10; } bufff=KeyIn3; //buf = 0,keyIn2=0 TR1=1; } //自己设置闹钟 00:00:10 if(sec==10) { BUZZ=~BUZZ; for(tt=0;tt<2000;tt++); } } }
C51单片机,时钟时间显示,蜂鸣器一到指定时间可以响。