/******************************** 按独立按键使数码管加1 ********************************/ #include <reg52.h> #define uchar unsigned char sbit KEY = P1 ^ 0; //定义独立按键 bit KEYSTA = 1; //按键的初始状态 uchar code DispCode[] = {0xc0,0xf9,0xa4,0xb0, //共阳数码管 0x99,0x92,0x82,0xf8, 0x80,0x90,0x88,0x83, 0xc6,0xa1,0x86,0x8e}; void Timer0Init(); //定时器初始化函数 void KeyProcess(); //按键处理函数 void main() { Timer0Init(); KeyProcess(); } void Timer0Init() { TMOD |= 0x01; TH0 = 0xF8; //定时2MS TL0 = 0xCD; EA =1; ET0 = 1; TR0 = 1; } void KeyProcess() { bit lasttime = 1; //定义前一次按键值,初始化为1; uchar count = 0; //计数值初始化为0; KEY = 0x01; //按键初始化; P0 = DispCode[count]; //数码管初始化; while(1) { if (KEYSTA != lasttime) //如果“当前按键状态”与“前一次按键状态”不同,说明按键有动作; { if (lasttime == 1) //如果按键有动作了,那么前一次按键状态为“弹起”(lasttime == 1),说明按键按下时,会响应动作; { count++; if (count >= 16) //计数加到16清零,只用一个共阳数码管; { count = 0; } P0 = DispCode[count]; //共阳数码管显示相应的值; } lasttime = KEYSTA; //如果按键有动作,就更新前一次按键的值; } } } void Timer0IRQ() interrupt 1 //2MS中断一次 { static keybuf = 0xFF; //定义一个静态按键缓存变量,且值为FF;主要是暂存按键状态; TH0 = 0xF8; //重新写入初值; TL0 = 0xCD; keybuf = (keybuf << 1) | KEY; //左移一位,使当前的按键状态移到按键缓存中; if (keybuf == 0) //如果移8次,按键状态都为0,说明按键真正按下; { KEYSTA = 0; //确定按键状态为按键; } else if (keybuf == 0xFF) //如果移8次,按键状态都为1,说明按键未按下 { KEYSTA = 1; } }
时间: 2024-10-12 05:47:27