其实编程就是一个小模块一个小模块积累而成的,当我完成99秒倒计时,我就想加入按键检测模块
今天下午有点兴趣,就加入了两个按键,一个是上升按键,每次按下后数字加1
而按键二 就是启动和停止按键
当按下KEY4时 停止倒计时,按下另一个按键可以启动
当启动倒计时时,按下按键KEY3时就会停止,再按一次就会重新启动
数字最大可以加到999
与大家分享我不值一提的小程序 吧!程序风格是宋老师的风格
也不搞什么回复可见了 !大家有什么意见要提出,一起进步的好
另外,发表在网络上也是自己备份的,到时自己的计算机没有了,也好在这里找到
/******************************************************
项目名称:99秒倒计时
时间:2015-7-9 V1.0
目的:使用51单片机的定时器1实现99秒倒计时
单片机平台:KST51单片机开发平台-金沙滩单片机
注意:unsigned char 的取值范围为0-255
unsigned char 的取值范围为0-65535
要结合单片机的硬件来看程序
2015-7-18 V1.1
增加按键功能
增加显示为3位数码管
按键按住后,可以让数字上升,最大至999
增加按键功能停止或者启动,同一个按键实现功能
**********************************************************/
#include<reg52.h>
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit KEY3 = P2 ^6;
sbit KEY4 = P2 ^7;
bit flag = 1;
bit KeySta = 1;
bit KeySta_1 = 1;
unsigned int sec = 99;
unsigned char code LedChar[] ={
0xC0,0xF9,0xA4,0xB0,0x99, 0x92,0x82,0xF8,
0x80,0x90,0X88,0x83,0XC6,0xA1,0x86,0x8E
};
unsigned char LedBuff[6] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
void LedScan() //此函数实现Led的动态扫描
{
static unsigned char i = 0;
P0 = 0xFF;
P1 = (P1 & 0xF8)| i;
P0 = LedBuff[ i];
if(i < 2)
i++;
else
i = 0;
}
void Led()
{
LedBuff[0] = LedChar[sec % 10];
LedBuff[1] = LedChar[sec/10 %10];
LedBuff[2] = LedChar[sec/100 %10];
}
void main()
{
bit backup = 1; //按键值备份,保存前一次的扫描值
bit backup_1 = 1;
ENLED = 0;
ADDR3 = 1;
//定时器寄存器初始化
TMOD = 0X01;
TH0 = 0xFC; //1 ms定时
TL0 = 0x67;
EA = 1;
ET0 = 1;
TR0 = 1;
P2 = 0xF7; //P2.3 and P2.0 置 0 ,即Keyout1 keyout4输出低电平
while(1)
{
if(KeySta != backup) //当前状态与前次值不相等说明此时按键有动作
{
if(backup == 0) //如果前次值为0,则说明当前是弹起状态
{
flag = 0; //倒计时停止
sec++;
}
}
backup = KeySta; //更新备份为当前值,以备时行下次比较
if(KeySta_1 != backup_1) //Enter按键
{
if(backup_1 == 0)
{
flag = ~flag; //重新启动倒计时
}
}
backup_1 = KeySta_1;
Led();
}
}
//中断服务函数
void InterruptTimer0() interrupt 1
{
static unsigned int cnt = 0;
static unsigned char keybuf = 0xFF;
static unsigned char keybuf_1 = 0xFF;
//Range of "unsigned char" is 0 to 255
//Range of "unsigned int" is 0 to 65535
TH0 = 0xFC;
TL0 = 0x67;
cnt++;
LedScan();
keybuf = (keybuf << 1) | KEY4;
if(keybuf == 0)
{
KeySta = 0;
}
else if(keybuf == 0xFF)
{
KeySta = 1;
}
else
{
}
//end key4 pro
keybuf_1 = (keybuf_1 << 1) |KEY3;
if(keybuf_1 == 0)
{
KeySta_1 = 0;
}
else if(keybuf_1 == 0xFF)
{
KeySta_1 = 1;
}
else
{
}
//end the key3
if(cnt >= 1000 && flag == 1 )
{
cnt = 0;
if(sec >0)
sec --;
else
sec = 99;
}
}
|