按键状态机

多个按键共同控制,只有最先按下的那个一个按键作用,并且也只有作用的按键弹起后其他按键才起作用

void KeyScan(vodi)
{
	static char KeyValue;
	static int	KeyCnt1, KeyCnt2, KeyCnt3;
	
	switch (KeyValue)
	{
		case 0:
		if(key1 == 0)	//按键1按下
		{
			KeyCnt1++;
			if(KeyCnt1 >= 10)//消抖
			{
				KeyCnt1 = 0;
				KeyCnt2 = 0;
				KeyCnt3 = 0;
				KeyValue = 1;
			}
		}
		else
			KeyCnt1 = 0;
		
		if(key2 == 0)	//按键2按下
		{
			KeyCnt2++;
			if(KeyCnt2 >= 10)//消抖
			{
				KeyCnt1 = 0;
				KeyCnt2 = 0;
				KeyCnt3 = 0;
				KeyValue = 2;
			}
		}
		else
			KeyCnt2 = 0;
		if(key3 == 0)	//按键3按下
		{
			KeyCnt3++;
			if(KeyCnt3 >= 10)//消抖
			{
				KeyCnt1 = 0;
				KeyCnt2 = 0;
				KeyCnt3 = 0;
				KeyValue = 3;
			}
		}
		else
			KeyCnt3 = 0;
		break;
		
		case 1:
			if(key1 == 1) //按键1弹起
			{
				KeyValue = 0;
			}
			break;
		
		case 2:
			if(key2 == 1) //按键2弹起
			{
				KeyValue = 0;
			}
			break;	
		
		case 3:
			if(key3 == 1) //按键3弹起
			{
				KeyValue = 0;
			}
			break;
	}
}
    

一个按键有单击,双击,长按多种状态


typedef enum{
	Key_Up = 0;
	Key_Click,
	Key_OnceClick,
	Key_DoubleClick,
	Key_LongClick
}KeyState


void KeyScan(vodi)
{
	static KeyState key_state = KeyUp_State;
	static int	KeyCnt;
	
	switch (key_state)
	{
		case KeyUp_State:
			if(key == 0)	//按键按下
			{
				KeyCnt++;
				if(KeyCnt >= 10)//消抖
				{
					KeyCnt = 0;
					KeyUp_State = Key_Click;
				}
			}
			else
				KeyCnt = 0;
			break;
		
		case Key_Click:
			KeyCnt++; //按下计数
			if(KeyCnt < 3000)  
			{
				if(key == 1) //按键弹起
				{
					KeyUp_State = Key_OnceClick;	//单击
					KeyCnt = 0;
				}
			}
			else	//按下3s
			{
				KeyCnt = 0;
				KeyUp_State = Key_LongClick;	//长按
			}
			break;
		
		case Key_OnceClick:
			KeyCnt++;	//弹起计数
			if(KeyCnt < 500)
			{
				if(key == 0)	//按键按下
				{
					KeyState = Key_DoubleClick;	//双击
				}
			}
			else	//超过500ms没按键按下
			{
				KeyState = KeyUp_State;	//空闲状态
			}
			break;	
		
		case Key_DoubleClick:
			if(key == 1) //按键弹起
			{
				key_state = KeyUp_State;
			}
			break;
			
		case Key_LongClick:
			if(key == 1) //按键弹起
			{
				key_state = KeyUp_State;
			}
			break;
	}
}
posted @ 2020-06-04 15:52  D·Kingson.Mo  阅读(241)  评论(0编辑  收藏  举报