A. 51單片機6位數碼管顯示時間
C51單片機六位數碼管時鍾
用數碼管dot分隔時分秒
用三個按鍵設置時間:
SET鍵:小時設定->分鍾設定->結束設定,小時設定狀態時表示小時的兩位數碼管閃爍,分鍾設定時表示分鍾的兩位數碼管閃爍
CHANGE鍵:在小時設定狀態和分鍾設定狀態改變數值
SET S鍵:秒置零
C語言代碼:
//main.c
#include <REGX52.H>
typedef unsigned int UINT ;
typedef unsigned char UCHAR ;
#define KEY P2
#define KEYMASK 0x07
sbit LE1 = P2^6; //定義位控口
sbit LE2 = P2^7; //定義段控口
UCHAR KeyPressDown = 0x00;
UCHAR KeyRelease = 0x00;
UCHAR LastKey = 0x00;
UCHAR MODE ;
extern UCHAR HH;
extern UCHAR MM;
extern UCHAR SS;
extern bit T_CYCLE ;
extern void T0_Init(void); //初始化定時器,函數定義在Timer.c
UCHAR code NUM[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
void delay(UINT t) //延時t時鍾周期
{
while (t--) ;
}
void H_Increase(void) //小時增1
{
if(HH<23) HH++;
else
{
HH = 0;
}
}
void M_Increase(void) //分鍾增1
{
if(MM<59) MM++;
else
{
MM = 0;
H_Increase();
}
}
void S_Increase(void) //秒增1
{
if(SS<59) SS++;
else
{
SS = 0;
M_Increase();
}
}
void display(UCHAR SEG,UCHAR Digi) //顯示一位數碼管,SEG = 0-9數字,Digi = 第0-6位
{
LE2 = 1;
P0 = (0x01<<Digi) ;
LE2 = 0;
P0 = 0x00;
LE1 = 1;
P0 = NUM[SEG];
if (Digi==1||Digi==3) P0 &= 0x7f ; //顯示分隔符
delay(50);
P0 = 0xff;
LE1 = 0;
}
void main(void)
{
P0 = 0xff;
LE1 = 0;
LE2 = 0;
T0_Init();
while(1)
{
if(MODE != 1 || T_CYCLE)
{
display(HH/10,0); //顯示小時十位數
display(HH%10,1); //顯示小時個位數
}
if(MODE != 2 || T_CYCLE)
{
display(MM/10,2); //顯示分鍾十位數
display(MM%10,3); //顯示分鍾個位數
}
display(SS/10,4); //顯示秒十位數
display(SS%10,5); //顯示秒個位數
}
}
void key_Process(void) //按鍵處理程序
{
UCHAR CurrKey;
KEY |= KEYMASK; //將按鍵對應的IO設置為輸入狀態
CurrKey = (~KEY) & KEYMASK;
KeyPressDown = (~LastKey) & CurrKey;
KeyRelease = LastKey & (~CurrKey);
LastKey = CurrKey;
switch(KeyRelease)
{
case 1:
if(MODE == 2) MODE = 0;
else MODE ++;
break;
case 2:
if(MODE == 1) H_Increase() ;
if(MODE == 2) M_Increase() ;
break;
case 4:
SS = 0;
break;
default: break;
}
}
//Timer.c
#include <reg52.h>
typedef unsigned int UINT ;
typedef unsigned char UCHAR ;
UCHAR HH = 14; //小時初始值
UCHAR MM = 2; //分鍾初始值
UCHAR SS = 55; //秒初始值
UINT u_10ms = 0; //10ms計數
bit T_CYCLE = 0;
extern void key_Process(void);
extern void S_Increase(void);
void T0_Init(void)
{
TMOD &= 0xf0;
TMOD |= 0x01;
//定時器賦初始值,定時時間為10ms。
TH0 = 0xd8;
TL0 = 0xf0;
TR0 = 1;
IE = 0x82;
}
void T0_INTSrv(void) interrupt 1
{
//定時器重新開始計時。
TH0 = 0xd8;
TL0 = 0xf0;
u_10ms ++;
if (u_10ms%20==0) // 200 ms
{
T_CYCLE = ! T_CYCLE; //閃爍循環
}
if (u_10ms>99) // 1000 ms = 1 second
{
u_10ms = 0;
S_Increase();
}
key_Process(); //SET按鍵處理
}
Proreus模擬電路:
B. 51單片機控制數碼管顯示時鍾,獨立按鍵怎麼弄
獨立按鍵處理起來是非常簡單的,一般都是IO口單獨控制,所以只需要消抖和判斷按鍵按下抬起狀態就好。比如:
sbitkey=P1^0;
if(key==0)
{
delay(10);
if(key==0)
{
keyval=1;
while(key==0);
}
}