本帖最后由 cumthe 于 2013-9-29 09:44 编辑
闲来无事,写了一个小程序,欢迎讨论和拍砖。
扫描在定时器中应该占不了太多资源。
enum Btn{NoClick = 0,ShortClick,DoubleClick,LongClick};
enum Btn BtnState = NoClick ;
#define LongClickTime 1000UL
#define DoubleClickTimeDur 200
定时器中:
static unsigned int count = 0,ShortClickFlag = 0,ShortClickFlagCount = 0;
if(SW == 0)
{
count++;
}
else
{
if(count>=5 && count < LongClickTime)
{
if(ShortClickFlag == 1)
{
ShortClickFlag = 0;
BtnState = DoubleClick;
}
else
{
ShortClickFlag = 1;
}
}
else if(count >= LongClickTime)
{
BtnState = LongClick;
}
count = 0;
if(ShortClickFlag == 1)
{
if(ShortClickFlagCount++ > DoubleClickTimeDur)
{
BtnState = ShortClick;
ShortClickFlag = 0;
ShortClickFlagCount = 0;
}
}
else
{
ShortClickFlagCount = 0;
}
}
主函数中:
注意在使用BtnState 后,需将其置位NoClick
switch(BtnState)
{
case NoClick:
break;
case ShortClick:
BtnState = NoClick;
break;
case DoubleClick:
BtnState = NoClick;
break;
case LongClick:
BtnState = NoClick;
break;
}
修改后:
定时器中:
static unsigned int count = 0,ShortClickFlagCount = 0;
//count为按键按下计时变量;ShortClickFlagCount为单击按键后超时判断是否有双击计时变量
static unsigned char ShortClickFlag = 0,LongClickFlag = 0;
//ShortClickFlag为单击按键标志,判断双击时用;LongClickFlag为长按按键标志,防止按键按下不释放
if(SW == 0)
{
if(count < LongClickTime)
{
count++;
}
else
{
BtnState = LongClick;
LongClickFlag = 1;
}
}
else
{
if(count>=5 && count < LongClickTime)
{
if(ShortClickFlag == 1)
{
ShortClickFlag = 0;
BtnState = DoubleClick;
}
else
{
ShortClickFlag = 1;
}
}
else if(count >= LongClickTime && LongClickFlag == 0)
{
BtnState = LongClick;
}
LongClickFlag = 0;
count = 0;
if(ShortClickFlag == 1)
{
if(ShortClickFlagCount++ > DoubleClickTimeDur)
{
BtnState = ShortClick;
ShortClickFlag = 0;
ShortClickFlagCount = 0;
}
}
else
{
ShortClickFlagCount = 0;
}
}
主函数中:
注意在使用BtnState 后,需将其置位NoClick
switch(BtnState)
{
case NoClick:
break;
case ShortClick:
BtnState = NoClick;
break;
case DoubleClick:
BtnState = NoClick;
break;
case LongClick:
BtnState = NoClick;
break;
default:
break;
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
嗯。最好加上default。
不是最好加上,而是一定要加上。
一周热门 更多>