经典的按键处理程序
扫描二维码
随时随地手机看文章
//***************精典按键处理程序*********************\
//单片机型号STC12C5204AD
//按键输入口:P2^0,P2^1
//输出端口:P2^2
#include
#define null 0x00
#define bit_0 0x01
#define bit_1 0x02
#define bit_2 0x04
#define bit_3 0x08
#define bit_4 0x10
#define bit_5 0x20
#define bit_6 0x40
#define bit_7 0x80
#define uchar unsigned char
#define suchar static unsigned char
#define uint unsigned int
#define suint static unsigned int
#define cuchar const unsigned char
#define uchar unsigned char
sbit OUT_LIGHT = P2^2; //定义背光驱动口
bit LOCK=0;
char keybitbuf;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
typedef struct // 按键处理用
{ uchar timebuf[8];
uchar hadpresskey;
} PressKey;
PressKey presskey;
#define WAITCIRCLETIMENUM 10// 20 //等待延时次数
/*按键检测*/
char lookForKey(PressKey *b,uchar *a,uchar BITNUM)
{ uchar m,n;
n=BITNUM,m=0;
while (!(n&1)) { m+=1;n=n>>1;}
if (b->hadpresskey&(*a)&BITNUM)
{ b->hadpresskey&=~BITNUM;
return(BITNUM);
}
else { if (*a&BITNUM)
{ b->timebuf[m]=0;
b->hadpresskey&=~BITNUM;
}
else { if (b->timebuf[m]>=WAITCIRCLETIMENUM )
{ b->hadpresskey|=BITNUM;
b->timebuf[m]=0;
}
else {b->timebuf[m]++; }
}
}
return(0);
}
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//程序的调用
void main()
{
while(1)
{
keybitbuf=P2; //P2表示单片机的P2口
if (lookForKey(&presskey,&keybitbuf,0x02)) {OUT_LIGHT=~OUT_LIGHT;} //0X02表示P2.1口,0X01表示P2.0,0X04表示P2.2 ,0X08表示P2.3,0X10表示P2.4
if (lookForKey(&presskey,&keybitbuf,0x01)) {OUT_LIGHT=~OUT_LIGHT; ;}
if (lookForKey(&presskey,&keybitbuf,0x20)) { ;}
}
}