新手入门
- 积分
- 17
- 金钱
- 17
- 注册时间
- 2021-11-27
- 在线时间
- 5 小时
|
//key.h文件
#ifndef _KEY_H_
#define _KEY_H_
#include"stm32f1xx_hal.h"
#define CONFIRM_TIME 5
#define LONG_PRESS_TIME 1000
uint8_t Key_Scan(void);
typedef enum {
KEY_RELEASE = 0,//释放松开
KEY_CONFIRM,//消抖
KEY_SHORTPRESS,//短按
KEY_LONGPRESS,//长按
} ButtonState;
#endif
//key.c文件
#include"key.h"
ButtonState buttonState = KEY_RELEASE;
uint32_t buttonPressTime = 0;
uint8_t Key_Scan(void)
{
uint64_t curSysTime;
switch (buttonState) {
case KEY_RELEASE:
if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13) == GPIO_PIN_RESET) {
buttonState = KEY_CONFIRM;
buttonPressTime = HAL_GetTick();
}
return 0;
break;
case KEY_CONFIRM:
if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13) == GPIO_PIN_RESET) {
//buttonState = KEY_RELEASE;
curSysTime = HAL_GetTick();
if(curSysTime -buttonPressTime > CONFIRM_TIME){
buttonState = KEY_SHORTPRESS;
}
} else {
buttonState = KEY_RELEASE;
}
break;
case KEY_SHORTPRESS:
if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13) == GPIO_PIN_SET) {
buttonState = KEY_RELEASE;
return 1;//返回按键码值,短按状态
} else {
curSysTime = HAL_GetTick();
if(curSysTime - buttonPressTime > LONG_PRESS_TIME ){
buttonState = KEY_LONGPRESS;
}
}
break;
case KEY_LONGPRESS:
if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13) == GPIO_PIN_SET) {
buttonState = KEY_RELEASE;
return 2;
}
break;
default :buttonState = KEY_RELEASE;
break;
}
return 0;
}
|
|