//基于51單片機的八位數(shù)字秒表
//開發(fā)語言:C51
//所選芯片:AT89S51
#include
#include
#define DIG_NONE 0xff;
#define DIG_1 0x7f
#define DIG_2 0xbf
#define DIG_3 0xdf
#define DIG_4 0xef
#define DIG_5 0xf7
#define DIG_6 0xfb
#define DIG_7 0xfd
#define DIG_8 0xfe
#define LINE 0xf7//根據(jù)共陰共陽以及接法要調(diào)整
typedef unsigned char Byte;
typedef bit bool;
sbit START = P3^0;
sbit RESET = P3^1;
Byte data dis_digit;
Byte data min;
Byte data sec;
Byte data msec;
bool data isStarted;
Byte data dis_digit;
Byte data dis_index;
Byte data dis_buff[8];
Byte data dis_num[8];
//根據(jù)共陰共陽以及數(shù)碼管接法這里要的表要調(diào)整
Byte code number[11]={ 0x28, 0x7E, 0xA2, 0x62, 0x74, 0x61, 0x21, 0x7A, 0x20, 0x60,0xff};//0,1,2,3,4,5,6,7,8,9,關顯示,數(shù)碼管碼表
Byte dis_buff[8]; // 顯示緩沖區(qū)
Byte dis_num[8]; // 秒計數(shù)值, BCD碼
Byte dis_index;
bit Scan_Key();
void Proc_Key();
void Delayms(Byte ms);
void Update_buff();
void Msec_Increment();
void Reset(void);
bool Get_Key(bit key);//有效為1
void MCU_Init(void);
void Timer0_Overflow();
void Timer1_Overflow();
//sbit K1 = P3^2;
void Msec_Increment()//中斷里面的設置
{
msec += 1;
if (msec == 100)
{
msec = 0;
sec += 1;
}
if (sec == 60)
{
sec = 0;
min += 1;
}
if (min == 60)
min = 0;
}
void MCU_Init()
{
P1 = 0xff;
P2 = 0xff;
TMOD = 0x12;
TH1 = 0xd8;
TL1 = 0xf0;
TH0 = 0x9c;
TL0 = 0x00;
////定時器1選用方式1工作,掃描周期0.01s=10ms,定時器0選用工作方式3工作,自動裝入,掃描周期0.1ms=100μs
Reset();
min = 0;
sec = 0;
msec = 0;
dis_digit = 0x7f; // 初始顯示P20口數(shù)碼管
dis_index = 0;
IE = 0x8a; // 使能timer0, timer1中斷
TR0 = 1;
TR1 = 0;
isStarted = 0;
}
void Reset()
{
min = 0;
sec = 0;
msec = 0;
Update_buff();
}
void Update_buff()
{
dis_num[0] = min / 10;
dis_num[1] = min % 10;
dis_num[3] = sec / 10;
dis_num[4] = sec % 10;
dis_num[6] = msec / 10;
dis_num[7] = msec % 10;
//這里根據(jù)數(shù)碼管的順序進行調(diào)整
dis_buff[0] = number[dis_num[7]];
dis_buff[1] = number[dis_num[6]];
dis_buff[2] = LINE;
dis_buff[3] = number[dis_num[4]];
dis_buff[4] = number[dis_num[3]];
dis_buff[5] = LINE;
dis_buff[6] = number[dis_num[1]];
dis_buff[7] = number[dis_num[0]];
}
bool Get_Key(bit key)//有效為1,這里按下為低電平
{
if (key == 0)
return 1;
else
return 0;
}
void timer0() interrupt 1
{
P2 = 0xff; // 先關閉所有數(shù)碼管
P1 = dis_buff[dis_index]; // 顯示代碼傳送到P0口
P2 = dis_digit; //
dis_digit = _cror_(dis_digit,1); // 位選通值右移(P20<-P27), 下次中斷時選通下一位數(shù)碼管
//_cror_()為字符循環(huán)右移函數(shù)
dis_index++; //
dis_index &= 0x07; // 8個數(shù)碼管全部掃描完一遍之后,再回到第一個開始下一次掃描
}
void timer1() interrupt 3
{
TH1 = 0xd8;
TL1 = 0xf0;
Msec_Increment();
Update_buff();
}
void delayms(unsigned char ms)
// 延時子程序
{
unsigned char i;
while(ms--)
{
for(i = 0; i < 120; i++);
}
}
void main(void)
{
bool startkey, resetkey;
MCU_Init();
while(1)
{
startkey = Get_Key(START);
resetkey = Get_Key(RESET);
if (startkey == 1)
{
Delayms(50);
startkey = Get_Key(START);
if (startkey == 1)
{
isStarted = !isStarted;
TR1 = !TR1;
}
}
if (resetkey == 1 && isStarted == 0)
{
Delayms(20);
resetkey = Get_Key(RESET);
if (resetkey == 1 && isStarted == 0)
{
Reset();
}
}
}
}