按键功能 优化
按键代码优化,主要有以下几点:1. 统一按键编码,单个按键以及组合按键
typedef enum
{
KeyID_None = 0,
KeyID_SingKey_Begin = KeyID_None,
KeyID_K1,
KeyID_K2,
KeyID_K3,
KeyID_JOY_U,
KeyID_JOY_D,
KeyID_JOY_L,
KeyID_JOY_R,
KeyID_JOY_OK,
KeyID_SingKey_End,
KeyID_CombKey_Begin,
KeyID_Comb_K13,
KeyID_Comb_K23,
KeyID_CombKey_End
} key_id_e;
使用 额外的枚举值生成宏变量, 为 bsp_key.c 文件提供按键数目信息
#define KEY_SINGLE_NUM(KeyID_SingKey_End - KeyID_SingKey_Begin - 1)
#define KEY_COMB_NUM (KeyID_CombKey_End - KeyID_CombKey_Begin - 1)
#define KEY_TOTAL_NUM (KEY_SINGLE_NUM + KEY_COMB_NUM)
2. 使用函数指针,屏蔽底层
1 和 2 确保了 bsp_key.c 和具体设备无关, 不同开发板代码移植时,只需要修改 bsp_key.h 的枚举类型 key_id_e 以及 bsp_key_ll.c 文件,后者提供了底层实现
3. 尽可能将结构体放在bsp_key.c 文件,
4. 按键缓冲中每个buffer 存放 uint8_t 类型,该类型包含按键 ID 和 按键状态信息
#define GET_KEY_CODE(id, status)(uint8_t)(((uint8_t)status << 5) + ((uint8_t)id & 0x1F))
#define GET_KEY_ID(code) (key_id_e)(code & 0x1F)
#define GET_KEY_STATE(code) (key_state_e)(code >> 5)
5. 待优化:
bsp_KeyScan10ms 不需要暴露出来,而是在 bsp_InitKey 将函数注册到 定时扫描函数数组,
按键状态也支持函数注册,当某个按键状态发生时,调用之前注册的函数。
细节都在代码中,就4个文件不同,bsp_key.c, bsp_key.h, bsp_key_ll.c 以及 bsp_key_ll.h
谢谢楼主分享。 不考虑0x1abin/MultiButton的么,防抖更强哦
#define DEBOUNCE_TICKS 3 //MAX 7 (0 ~ 7)
/*------------button debounce handle---------------*/
if(read_gpio_level != handle->button_level) { //not equal to prev one
//continue read 3 times same new level change
if(++(handle->debounce_cnt) >= DEBOUNCE_TICKS) {
handle->button_level = read_gpio_level;
handle->debounce_cnt = 0;
}
} else { //level not change ,counter reset.
handle->debounce_cnt = 0;
}
页:
[1]