单片机矩阵键盘扫描的两种方式
扫描二维码
随时随地手机看文章
矩阵键盘扫描方式:
第一种:逐行扫描法,就是一行一行的扫描。实现代码如下(键盘连接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;
}
第二种,线性反转法。就是行和列分别读出。实现代码如下:
#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;
}