- #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;
- }
- }
- }
复制代码 |