一、独立按键优化
unsigne char key_up = 1; //松手标志位
unsigned char Key_Scan()
{
if(key_up == 1 && (S7 == 0 || S6 == 0 || S5 == 0 || S4 == 0)) //标志位为1且四个按键有一个按键按下时
{
key_up = 0; //按下
delay_ms(20);
if(S7 == 0) return 1;
else if(S6 == 0) return 2;
else if(S5 == 0) return 3;
else if(S4 == 0) return 4;
}
else if(S7 == 1 && S6 == 1 && S5 == 1 && S4 == 1)) //四个按键都未按下时
key_up = 1;
return 0;
}
二、矩阵键盘优化
矩阵键盘行列扫描:
unsigned char key_up = 1; //松手标志位
unsigned char Key_Scan()
{
unsigned char key;
P44 = P42 = P35 = P34 = 1;
P30 = P31 = P32 = P33 = 0;
if(key_up == 1 && (P44 == 0 || P42 == 0 || P35 == 0 || P34 == 0)) //标志位为1且四个按键有一个按键按下时
{
key_up = 0; //按下
delay_ms(20);
if(P44 == 0) key = 1;
else if(P42 == 0) key = 2;
else if(P35 == 0) key = 3;
else if(P34 == 0) key = 4;
P44 = P42 = P35 = P34 = 0;
P30 = P31 = P32 = P33 = 1;
if(key_up == 1 && (P30 == 0 || P31 == 0 || P32 == 0 || P33 == 0))
{
delay_ms(20);
if(P30 == 0) key = key;
else if(P31 == 0) key = key + 4;
else if(P32 == 0) key = key + 8;
else if(P33 == 0) key = key + 12;
}
return key;
}
else if(P44 == 1 && P42 == 1 && P35 == 1 && P34 == 1))
key_up = 1;
return 0;
}