利用定时器T0、数码管模块和2个独立按键(J5的2-3短接),设计一个秒表,具有清零、暂停、启动功能
显示格式:分-秒-0.05秒(50ms)
S4:暂停/启动
S5:清零
//利用定时器T0、数码管模块和2个独立按键(J5的2-3短接),设计一个秒表,具有清零、暂停、启动功能
#include "reg52.h"
sbit S4 = P3^3;
sbit S5 = P3^2;
unsigned char code SMG_duanma[18]= //code 是表格形式
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,
0xbf,0x7f};
unsigned char t_m = 0;
unsigned char t_s = 0;
unsigned char t_005s = 0;
void SelectHC573(unsigned char channel)
{
switch (channel)
{
case 4: P2 = (P2 & 0x1f) | 0x80; break; //LED寄存器的选通端
case 5: P2 = (P2 & 0x1f) | 0xa0; break; //
case 6: P2 = (P2 & 0x1f) | 0xc0; break; //数码管位选锁存器
case 7: P2 = (P2 & 0x1f) | 0xe0; break; //数码管的段选锁存器
}
}
void DisplaySMG_Bit(unsigned char value, unsigned char pos) //数码管的动态显示
{
SelectHC573(6);
P0 = 0x01 << pos;
SelectHC573(7);
P0 = value;
}
void DelaySMG(unsigned int t)
{
while(t--);
}
void DisplayTime()
{
DisplaySMG_Bit(SMG_duanma[t_005s%10],7);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[t_005s/10],6);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[16],5);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[t_s%10],4);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[t_s/10],3);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[16],2);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[t_m%10],1);
DelaySMG(500);
DisplaySMG_Bit(SMG_duanma[t_m/10],0);
DelaySMG(500);
}
//=============定时器相关函数========================
void InitTimer0()
{
TMOD = 0X01;
TH0=(65535-50000)/256;
TL0=(65535-50000)%256;
ET0=1;
EA=1;
TR0=1;
}
void ServiceTimer0 () interrupt 1
{
TH0=(65535-50000)/256; //计数初值重装 一定不能漏掉!!!!!
TL0=(65535-50000)%256;
t_005s++;
if(t_005s == 20)
{
t_s++;
t_005s = 0;
if(t_s == 60)
{
t_m++;
t_s = 0;
}
if(t_m == 99)
{
t_m = 0;
}
}
}
//===================================================
void DelayK(unsigned char t) //按键去抖的延时函数
{
while(t--);
}
void ScanKeys()
{
if(S4 == 0)
{
DelayK(100);
if (S4 == 0) //秒表启动与暂停
{
TR0= ~TR0;
}
}
if(S5 == 0)
{
DelayK(100);
if (S5 == 0) //秒表清零
{
t_m = 0;
t_s = 0;
t_005s = 0;
}
}
}
void main()
{
InitTimer0();
while(1)
{
DisplayTime();
ScanKeys();
}
}