本帖最后由 desgh 于 2012-6-6 17:42 编辑
void GetKey(uint8 *pKeyValue)
{
static uint8 s_u8KeyState = KEY_STATE_INIT ;
static uint8 s_u8KeyTimeCount = 0 ;
static uint8 s_u8LastKey = KEY_NULL ; //保存按键释放时候的键值
uint8 KeyTemp = KEY_NULL ;
KeyTemp = KeyScan() ; //获取键值
switch(s_u8KeyState)
{
case KEY_STATE_INIT :
{
if(KEY_NULL != (KeyTemp))
{
s_u8KeyState = KEY_STATE_WOBBLE ;
}
}
break ;
case KEY_STATE_WOBBLE : //消抖
{
s_u8KeyState = KEY_STATE_PRESS ;
}
break ;
case KEY_STATE_PRESS :
{
if(KEY_NULL != (KeyTemp))
{
s_u8LastKey = KeyTemp ; //保存键值,以便在释放按键状态返回
键值
KeyTemp |= KEY_DOWN ; //按键按下
s_u8KeyState = KEY_STATE_LONG ;
}
else
{
s_u8KeyState = KEY_STATE_INIT ;
}
}
break ;
case KEY_STATE_LONG :
{
if(KEY_NULL != (KeyTemp))
{
if(++s_u8KeyTimeCount > KEY_LONG_PERIOD)
{
s_u8KeyTimeCount = 0 ;
KeyTemp |= KEY_LONG ; //长按键事件发生
s_u8KeyState = KEY_STATE_CONTINUE ;
}
}
else
{
s_u8KeyState = KEY_STATE_RELEASE ;
}
}
break ;
case KEY_STATE_CONTINUE :
{
if(KEY_NULL != (KeyTemp))
{
if(++s_u8KeyTimeCount > KEY_CONTINUE_PERIOD)
{
s_u8KeyTimeCount = 0 ;
KeyTemp |= KEY_CONTINUE ;
}
}
else
{
s_u8KeyState = KEY_STATE_RELEASE ;
}
}
break ;
case KEY_STATE_RELEASE :
{
s_u8LastKey |= KEY_UP ;
KeyTemp = s_u8LastKey ;
s_u8KeyState = KEY_STATE_INIT ;
}
break ;
default : break ;
}
*pKeyValue = KeyTemp ; //返回键值+按键状态
}
上面是原文,修改了下,大家多多指点:
void GetKey(uint8 *pKeyValue) //获取键值
{
static uint8 s_u8KeyState = KEY_STATE_INIT ; //
static uint8 s_u8KeyTimeCount = 0 ; //
static uint8 s_u8LastKey = KEY_NULL ;
uint8 KeyTemp = KEY_NULL ; //
KeyTemp = KeyScan() ; //获取键值
switch(s_u8KeyState)
{
case KEY_STATE_INIT:
{
if(KEY_NULL != (KeyTemp) )
{
s_u8KeyState = KEY_STATE_WOBBLE ;
}
}
break ;
case KEY_STATE_WOBBLE :
{
s_u8KeyState = KEY_STATE_PRESS ;
}
break ;
case KEY_STATE_PRESS : //消抖
{
if(KEY_NULL != (KeyTemp) )
{
s_u8LastKey = KeyTemp ; //保存键值
s_u8LastKey |= KEY_DOWN ;
s_u8KeyState = KEY_STATE_LONG ;
}
else
{
s_u8KeyState = KEY_STATE_INIT ;
}
}
break ;
case KEY_STATE_LONG:
{
if(KEY_NULL != (KeyTemp) )
{
if(++s_u8KeyTimeCount > KEY_LONG_PERIOD )
{
s_u8KeyTimeCount = 0 ;
s_u8LastKey &= 0x0f;
s_u8LastKey |= KEY_LONG ;
s_u8KeyState = KEY_STATE_CONTINUE ;
}
}
else
{
s_u8KeyState = KEY_STATE_RELEASE ;
}
}
break ;
case KEY_STATE_CONTINUE :
{
if(KEY_NULL != (KeyTemp) )
{
if(++s_u8KeyTimeCount > KEY_CONTINUE_PERIOD )
{
s_u8KeyTimeCount = 0 ;
s_u8LastKey &= 0x0f;
s_u8LastKey |= KEY_CONTINUE ;
}
}
else
{
s_u8KeyState = KEY_STATE_RELEASE ;
}
}
break ;
case KEY_STATE_RELEASE :
{
KeyTemp = s_u8LastKey ;
s_u8LastKey |= KEY_UP ;
s_u8KeyState = KEY_STATE_INIT ;
}
break ;
default : break;
}
*pKeyValue = KeyTemp ; //返回键值
}
还望各位多交流交流!
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
多谢指导!
学艺不精,惭愧了!
这样写就是简化在主程序 中还要去判断 KEY_UP,所以做了点小改动!嘻嘻! 等到按键释放了才返回值,当然了如果你是不需要这样做 ,比方说长按后数据会连续增加,或者连发数据会连续增加就不用等到按键释放了!
一周热门 更多>