矩陣鍵盤掃描方式:
第一種:逐行掃描法,就是一行一行的掃描。實現(xiàn)代碼如下(鍵盤連接P2口):
#define NO_KEY 0XFF
#define KEY_LO() P2 &= 0XF0
#define KEY_HI() P2 |= 0X0F
#define KEY_L(i) P2 &= ~(1<
#define KEY_RD() ((P2>>4) & 0x0f)
UINT8 OnceKey(void)
{
UINT8 line = 0;
UINT8 key = NO_KEY;//key value
KEY_LO();
if (KEY_RD() == 0X0F)
{
KEY_HI();
return NO_KEY;
}
for (line=0; line<4; line ++)
{
KEY_HI();
KEY_L(line);
key = KEY_RD();
switch (key)
{
case ROW_FIRST:
key = 4*line + 0;
break;
case ROW_SECOND:
key = 4*line + 1;
break;
case ROW_THIRD:
key = 4*line + 2;
break;
case ROW_FOURTH:
key = 4*line +3;
break;
default :
key = 0x0f;
break;
}
if (key < 0x10)
{
return key;
}
}
return NO_KEY;
}
第二種,線性反轉(zhuǎn)法。就是行和列分別讀出。實現(xiàn)代碼如下:
#define CVT(i) ((i)==(~1)&0x0f)? 0: ((i)==(~2)&0x0f)? 1: ((i)==(~4)&0x0f)? 2: ((i)==(~8)&0x0f)? 3: 4;
#define KEY0_3HI() P2 |= 0X0F
#define KEY0_3LO() P2 &= 0XF0
#define KEY4_7HI() P2 |= 0XF0
#define KEY4_7LO() P2 &= 0X0F
#define KEY0_3RD() (P2 & 0X0F)
#define KEY4_7RF() ((P2>>4) & 0X0F)
UINT8 OnceKey(void)
{
UINT8 line = NO_KEY;
UINT8 row = NO_KEY;
UINT8 key;
KEY0_3HI();
KEY4_7LO();
line = KEY0_3RD();//讀入行的值
if (0x0f == line)
{
key = NO_KEY;
}
else
{
KEY0_3LO();
KEY4_7HI();
row = KEY4_7RD();//讀入列的值
if (0x0f == row)
{
key = NO_KEY;
}
else
{
key = CVT(line)*4 + CVT(row);
}
}
KEY0_3HI();
KEY4_7HI();
return key;
}