单片机按键扫描:
分别实现长按两秒运行一种功能,短按松开后运行另一种功能。
代码如下:
#define KEY1_PRES 1 //KEY1短按松开生效
#define KEY1_LONG_PRES 2 //KEY1长按2s生效
unsigned char Key1_Scan()
{
static unsigned char Key1_Flag=0;//按键按下类型 0:短按松开生效,长按2s生效
static unsigned char KeytimeCount=0;//按键按下时间统计
static unsigned char Key_up=1;//按键松开标志,按下时为1,松开时为0
if(MCU_KEY1==1 && Key_up==1)//按键按下
{
Delay(10);//延迟10ms 去抖动
if(MCU_KEY1==1)
{
Key_up=0;
Key1_Flag=0;
KeytimeCount=0;
}
}
if(MCU_KEY1==0 && Key_up==0)//按键松开
{
Key_up=1;
KeytimeCount=0;
if(Key1_Flag==0)
return KEY1_PRES;//KEY1短按 松开生效
}
if(MCU_KEY1==1)//如果按键长按2s则返回长按类型
{
Delay(1000);//1s
KeytimeCount++;
if(KeytimeCount==2)//按下按键时长,如果长按两秒返回长按类型
{
KeytimeCount=0;
Key1_Flag=1;
return KEY1_LONG_PRES;//KEY1长按
}
}
return 0;//无按键按下
}