65 lines
2.2 KiB
C
65 lines
2.2 KiB
C
#ifndef INCLUDED_DEBOUNCE_H
|
|
#define INCLUDED_DEBOUNCE_H
|
|
|
|
#ifndef INCLUDED_STDINT_H
|
|
#define INCLUDED_STDINT_H
|
|
#include <stdint.h>
|
|
#endif /*INCLUDED_STDINT_H*/
|
|
|
|
/* ------------------------------------------------------------------------------------------------------------------ */
|
|
/* */
|
|
|
|
typedef enum {
|
|
kButtonEvent_NONE = 0,
|
|
kButtonEvent_PRESS,
|
|
kButtonEvent_CLICK,
|
|
kButtonEvent_DOUBLE_CLICK,
|
|
kButtonEvent_LONG_PRESS,
|
|
kButtonEvent_RELEASE,
|
|
}ButtonEvent_t;
|
|
|
|
typedef enum{
|
|
kButtonState_IDLE = 0,
|
|
kButtonState_DEBOUNCE, /* 按下消抖 */
|
|
kButtonState_PRESS, /* 确认按下,等待释放或长按 */
|
|
kButtonState_LONG_PRESS, /* 处于长按状态 */
|
|
kButtonState_WAIT_DOUBLE, /* 等待第二次按下 */
|
|
kButtonState_DOUBLE_DEBOUNCE, /* 第二次消抖 */
|
|
kButtonState_RELEASE_DEBOUNCE, /* 释放消抖 */
|
|
}ButtonState_t;
|
|
|
|
typedef struct {
|
|
ButtonState_t state;
|
|
uint8_t debounce_cnt; /* 消抖计数器 */
|
|
uint16_t long_press_cnt; /* 长按计数器 */
|
|
uint16_t double_click_cnt; /* 双击等待计数器 */
|
|
uint8_t is_pressed; /* 经过消抖后当前的电平: (1:按下, 0:松开) */
|
|
uint8_t last_pressed; /* 上一次物理电平 */
|
|
}Debounce_t;
|
|
|
|
#define DEBOUNCE_INIT {kButtonState_IDLE, 0, 0, 0, 0, 0}
|
|
|
|
/* ------------------------------------------------------------------------------------------------------------------ */
|
|
/* */
|
|
|
|
// 核心参数配置(基于 10ms 状态机轮询周期)
|
|
#define DEBOUNCE_TICKS 3 // 消抖时间: 3 * 10ms = 30ms
|
|
#define DEBOUNCE_LONG_TICKS 150 // 长按判定: 150 * 10ms = 1.5s
|
|
#define DEBOUNCE_DOUBLE_TICKS 35 // 双击间隔: 35 * 10ms = 350ms
|
|
|
|
/* ------------------------------------------------------------------------------------------------------------------ */
|
|
/* */
|
|
|
|
void Debounce_Init(Debounce_t* self);
|
|
|
|
/**
|
|
* @brief 状态机核心处理函数(需在 10ms 定时器中断或主循环定时中调用)
|
|
* @param self: 消抖结构体指针
|
|
* @param cur_state: 当前按键状态,1:按下, 0:松开
|
|
* @return 检测到的事件类型
|
|
*/
|
|
ButtonEvent_t Debounce_Handle(Debounce_t* self, uint8_t cur_state);
|
|
|
|
|
|
#endif /*INCLUDED_DEBOUNCE_H*/
|