#define HAVEKEY_PIN 0x0003 //
#define KEYPOP 0x0000
#define KEY_START_PRESSED 1 //
typedef struct
{
INT8U bLastValue; //
INT8U bDebunceTime; //
INT8U bPressed; //
INT8U bValue; //
INT8U bState; //
} tKEY;
1. 按鍵IO口配置
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_KEY_PORT, ENABLE);
GPIO_InitStruct.GPIO_Pin = PAUSE_KEY_PIN | CLEAR_KEY_PIN ;//| ENTER_KEY_PIN | SET_KEY_PIN ;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN; //GPIO_Mode_AF,GPIO_Mode_OUT
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_2;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIO_KEY_PORT, &GPIO_InitStruct);
memset( &KeyCtrl,0,sizeof(tKEY));
}
2. 按鍵debunce時間,在timer裏調用
void KeyCtrlbDebunceTimeDec(void)
{
if(KeyCtrl.bDebunceTime)
{
KeyCtrl.bDebunceTime--;
}
else
{
KeyCtrl.bDebunceTime = 20;
}
}
3. 掃描按鍵
INT8U KeyScan(u8 *bKeyValue)
{
int TempKeyIn;
TempKeyIn = GPIO_ReadInputData(GPIO_KEY_PORT);
TempKeyIn = GPIO_ReadInputData(GPIO_KEY_PORT) & HAVEKEY_PIN; //get high 8 bit
TempKeyIn = (TempKeyIn ^ 0xffff) & HAVEKEY_PIN;
if(TempKeyIn == 0x0000) //no key pressed
{
memset( &KeyCtrl,0,sizeof(tKEY));
return NOKEY_PRESSED;
}
else
{
if(KeyCtrl.bState != KEY_START_PRESSED) //start key pressed
{
KeyCtrl.bState = KEY_START_PRESSED;
KeyCtrl.bDebunceTime = 20; //10ms
return NOKEY_PRESSED;
}
else
{
if(TempKeyIn == KeyCtrl.bLastValue) //lastkey
{
return NOKEY_PRESSED;
}
else
{
if(KeyCtrl.bDebunceTime !=0) //debunce time? 10ms
{
return NOKEY_PRESSED;
}
else
{
KeyCtrl.bLastValue = TempKeyIn;
KeyCtrl.bValue = TempKeyIn;
*bKeyValue = TempKeyIn;
return KEY_PRESSED;
}
}
}
}
}
4. 按鍵處理
void KeyPro(void)
{
u8 KeyValue;
if(KeyScan(&KeyValue) == KEY_PRESSED)
{
if(KeyValue == CLEAR_KEY)
{
ExtiCnt = 0;
}
else if(KeyValue == PAUSE_KEY)
{
PauseFlag = ~PauseFlag;
}
}
}