經(jīng)典的按鍵處理程序
//***************精典按鍵處理程序*********************\
//單片機(jī)型號(hào)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; //定義背光驅(qū)動(dòng)口
bit LOCK=0;
char keybitbuf;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
typedef struct // 按鍵處理用
{ uchar timebuf[8];
uchar hadpresskey;
} PressKey;
PressKey presskey;
#define WAITCIRCLETIMENUM 10// 20 //等待延時(shí)次數(shù)
/*按鍵檢測(cè)*/
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);
}
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//程序的調(diào)用
void main()
{
while(1)
{
keybitbuf=P2; //P2表示單片機(jī)的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)) { ;}
}
}