C语言《检测按键》

记录一下按键检测的快速算法

typedef  struct 
{
	uint16_t u16Value;//key value
	
	uint16_t u16Trg;//triger 
	
	uint16_t u16Cont;//continue
	bool boolPressed;
	
	uint16_t u16Release;//release
	bool boolReleased;				
	
}KEY_INFO;

u16Trg : 表示按键按下的状态
u16Release :表示释放的状态
u16Cont :按键值

1.检测

 //1.get key is pressed value.
u16Value = u16Value & DE_KEY_ALL;      

//2.triger pressed                                                      
g_KeyInfo.u16Trg     = u16Value & (u16Value ^ g_KeyInfo.u16Cont);      
  
 //3.triger released     
g_KeyInfo.u16Release = u16Value ^ g_KeyInfo.u16Trg ^ g_KeyInfo.u16Cont; 

//4.the key countinue press	
g_KeyInfo.u16Cont    = u16Value;										                                 

2.处理

static void Key_Process(void)
{

	//get the key released
	if(g_KeyInfo.u16Release)
	{
		g_KeyInfo.u16Value |= g_KeyInfo.u16Release;
	}
	//key pressed
	if(g_KeyInfo.u16Cont)
	{
		g_KeyInfo.boolPressed = TRUE;
	}

	//key released
	if((!g_KeyInfo.u16Cont)&&(g_KeyInfo.boolPressed))
	{
		g_KeyInfo.boolPressed  = FALSE;
		g_KeyInfo.boolReleased = TRUE;
	}
}
  1. 传值

    if(g_KeyInfo.boolReleased)
    {
    return g_KeyInfo.u16Value;
    }

你可能感兴趣的:(单片机)