实验功能:利用定时器实现秒表,通过按键S4启动或暂停,按键S5清零
代码:
#include <STC15F2K60S2.H>
#include "intrins.h"
sbit S4 = P3^3;
sbit S5 = P3^2;
unsigned char t_fen = 0;
unsigned char t_s = 0;
unsigned char t_ms = 0;
unsigned char code SMG_NoDot[18]={
0xc0,0xf9,0xa4,0xb0,0x99,0x92,//5
0x82,0xf8,0x80,0x90,0x88,
0x80,0xc6,0xc0,0x86,0x8e,
0xbf,0x7f};
void Delay1ms(int x);
void InitHC138(unsigned char n)
{
switch(n)
{
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void ShowSMG(unsigned char value,unsigned char pos)
{
InitHC138(6);
P0 = 0x01<<pos;
InitHC138(7);
P0 = value;
}
void DisplayInit()
{
ShowSMG(SMG_NoDot[t_ms % 10],7);Delay1ms(2);
ShowSMG(SMG_NoDot[t_ms / 10],6);Delay1ms(2);
ShowSMG(SMG_NoDot[16],5);Delay1ms(2);
ShowSMG(SMG_NoDot[t_s % 10],4);Delay1ms(2);
ShowSMG(SMG_NoDot[t_s / 10],3);Delay1ms(2);
ShowSMG(SMG_NoDot[16],2);Delay1ms(2);
ShowSMG(SMG_NoDot[t_fen % 10],1);Delay1ms(2);
ShowSMG(SMG_NoDot[t_fen / 10],0);Delay1ms(2);
}
void KeyInit()
{
if(S4 == 0)
{
Delay1ms(20);
if(S4 == 0)
{
TR0 = ~TR0;
while(S4 == 0);
}
}
if(S5 == 0)
{
Delay1ms(20);
if(S5 == 0)
{
t_fen = 0;
t_s = 0;
t_ms = 0;
while(S5 == 0);
}
}
}
void Timer0Init()
{
TMOD = 0x01;
TH0 = (65535-50000) / 256;
TL0 = (65535-50000) % 256;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void ServerInit() interrupt 1
{
TH0 = (65535-50000) / 256;
TL0 = (65535-50000) % 256;
t_ms++;
if(t_ms == 20)
{
t_s++;
t_ms = 0;
if(t_s == 60)
{
t_fen++;
t_s = 0;
}
}
if(t_fen == 99)
{
t_fen = 0;
}
}
void main()
{
Timer0Init();
while(1)
{
DisplayInit();
KeyInit();
}
}
void Delay1ms(int x) //@11.0592MHz
{
int y;
y = x;
while(x--)
{
unsigned char data i, j;
_nop_();
_nop_();
_nop_();
i = 11;
j = 190;
do
{
while (--j);
} while (--i);
}
x = y;
}
实验结果: