數(shù)字時鐘(數(shù)碼管顯示/鍵盤可調(diào))
有關(guān)的硬件原理圖:
c程序:
//溫馨提示:
/*程序還沒有調(diào)試完成,實(shí)際電路板調(diào)節(jié)時間時時-分-秒都會有閃爍現(xiàn)象,其實(shí)我是不知道的,why,也求解釋
#include
#include
sbit duan=P2^2; //定義鎖存使能端口 段鎖存
sbit wei=P2^3; // 位鎖存
sbit key1 = P1^1;
sbit key2 = P1^2;
sbit key3 = P1^3;
sbit key4 = P1^4;
unsigned char code duanma[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; // 顯示段碼值0~9
unsigned char code weima[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f}; //分別對應(yīng)相應(yīng)的數(shù)碼管點(diǎn)亮,即位碼
unsigned char temp[8]; //存儲顯示值的全局變量
char hour; minute; second, num, t, i;
//函數(shù)聲明
void delay(unsigned int t);
void initial();
void delay20ms();
void keyscan();
void caifen();
void display();
/*------------------------------------------------
主函數(shù)
------------------------------------------------*/
void main()
{
initial(); //調(diào)用初始化程序
while(1)
{
keyscan(); //調(diào)用鍵盤掃描
caifen(); //調(diào)用拆分以時-分-秒的形式
display(); //調(diào)用時間的顯示程序
}
}
//初始化程序
void initial()
{
TMOD = 0x01; //設(shè)置T1工作于定時方式1(有16位計(jì)數(shù))
TH0 = (65536 - 2000)/256; //定時器1賦初值,是TH1而不是TH0噢(若要設(shè)置是定時器0的話,把1改為0,下同);計(jì)數(shù)了2000次,即為2ms
TL0 = (65536 - 2000)%256;
EA = 1; //開中斷
TR0 = 1; //開定時器0
ET0 = 1; //開啟定時器中斷0
hour = 23; //賦初值
minute = 59; //賦初值
second = 57; //賦初值
}
//中斷服務(wù)程序
void time0(void) interrupt 1
{
TH0 = (65536 - 2000)/256; //重新賦值
TL0 = (65536 - 2000)%256;
num ++; //中斷500次后 即2ms X 500 = 1000MS = 1S,(一般可計(jì)數(shù)久點(diǎn)如50000ms,中斷20次,這樣誤差就不會太大)
if (num == 500)
{
num = 0;
second ++;
if (second == 60) //秒為60則miao置0,minute加一
{
second = 0;
minute ++;
if (minute == 60) //分為60則minute置0,hour加一
{
minute = 0;
hour ++;
if (hour == 24) //小時為24則hour置0
{
hour = 0;
}
}
}
}
}
//鍵盤掃描程序,可執(zhí)行時分的加減
void keyscan()
{
if(key1 == 0)
{
delay20ms(); //延時20ms,去抖動
while(key1 == 0); //等待(上升沿則執(zhí)行下一行,TRO = 0)
TR0 = 0; //關(guān)定時器0
t ++; //t++與調(diào)節(jié)時分秒有關(guān)
}
switch(t) //選擇調(diào)節(jié)時分秒有關(guān),與上面的t相關(guān)聯(lián)
{
case 1:
if(key2 == 0)
{
delay20ms();
if(key2 == 0)
{
while(key2 == 0);
hour ++;
if(hour == 24)
{
hour = 0;
}
}
}
if(key3 == 0)
{
delay20ms();
if(key3 == 0)
{
while(key3 == 0);
hour --;
if(hour == -1) //因?yàn)閔our是char型,所以可以有負(fù)數(shù),若是unsigned char則不允許,下面的minute同理
{
hour =23;
}
}
}
break;
case 2:
if(key2 == 0)
{
delay20ms();
if(key2 == 0)
{
while(key2 == 0);
minute ++;
if(minute == 60)
{
minute = 0;
}
}
}
if(key3 == 0)
{
delay20ms();