状态机检测矩阵键盘以及消抖的方法

也是参考的网上的博客的写法:

附上程序:

u8 scan_key()                        //可以判断读到的键值,但不具备消抖的能力
{
static u8 key_state = 0;
u8 key_return = 0;
u8 key_press;
u8 key1,key2;

P30=0;P31=0;P32=0;P33=0; P34=1;P35=1;P42=1;P44=1;        //行列翻转得特殊键值
if(P44==0) key1=0x70;                  //结合键盘位置设定
if(P42==0) key1=0xb0;
if(P35==0) key1=0xd0;
if(P34==0) key1=0xe0;
if( (P34==1)&&(P35==1)&&(P42==1)&&(P44==1) ) key1=0xf0;

P30=1;P31=1;P32=1;P33=1;P34=0;P35=0;P42=0;P44=0;
if(P30==0) key2=0x0e;
if(P31==0) key2=0x0d;
if(P32==0) key2=0x0b;
if(P33==0) key2=0x07;
if( (P30==1)&&(P31==1)&&(P32==1)&&(P33==1) ) key2=0x0f;

key_press=key1|key2;

switch(key_state)
{
case key_state_0:
if(key_press!=0xff)
key_state=key_state_1;        
break;
case key_state_1:
if(key_press!=0xff)
{
switch(key_press)
{
case 0x77: key_return=4;break;
case 0x7b: key_return=5;break;
case 0xb7: key_return=8;break;
case 0xbb: key_return=9;break;
}
key_state=key_state_2;

}
else key_state=key_state_0;break;

case key_state_2:
if(key_press==0xff) key_state=key_state_0;
break;
}

return key_return;

}

主函数中消抖:

if(key_flag==1)
{
key_flag=0;
x=scan_key();
if(x != old)
{
  old = x;

  if(x==???){处理的语句}

}

}

定时器中做扫描按键,得一个传递的标志位:

void irs_timer0() interrupt 1
{
static u8 count=0,count1=0;
count++;
TL0 = 0x66;     // 定时1ms
TH0 = 0xFC; 
if(count==10)
{
key_flag=1;
count=0;

}

原文地址:https://www.cnblogs.com/page71/p/13971306.html