目 录
- 按键单一动作识别
- 按键组合动作识别
按键单一动作识别
带有按键的作品设计时,按键动作检测是必不可少的,如何判断按键是单击、双击、三击和长按动作呢?
1、定时器定时一个10ms周期
2、把按键检测函数放到这个周期内执行,即10ms执行一次该函数
函数代码参考(已验证):
#define KEY_IO_STATUS (P11) //按下为LOW#define CONFIG_KEY_2S_PRESS_CNT (200)#define EVENT_UI_TRIPLE_CLICK (1 << 4)
#define EVENT_UI_DOUBLE_CLICK (1 << 3)
#define EVENT_UI_KEY_CLICK (1 << 2)void key_handle_10ms(void)
{static uint16_t key_0_pressed_cnt = 0;static bool key_prev_status = 0, key_is_pressing = 0, key_curt_status = 0;static uint8_t key_clik_cnt = 0, key_continue_flag = 0, key_interval_timer = 0;key_curt_status = KEY_IO_STATUS;//read status of key gpioif (!(key_prev_status ^ key_curt_status)){if (key_prev_status == 0){//上次为0,本次为0key_is_pressing = true;//按键按下} else {key_is_pressing = false;}}else {key_prev_status = key_curt_status;//状态不同时才更新}if (key_is_pressing){//按下时key_interval_timer = 0;key_0_pressed_cnt++;//时长计数} else {//松开后判断按下时长if ((key_0_pressed_cnt < CONFIG_KEY_2S_PRESS_CNT) && (key_0_pressed_cnt > 3)) {//增大key_0_pressed_cnt最小判断值,防误按if (key_continue_flag){if (++key_clik_cnt >= 4){key_continue_flag = 0;key_clik_cnt = 0;}}else{key_continue_flag = 1;key_clik_cnt = 1;}}key_0_pressed_cnt = 0;}if (key_continue_flag){if (key_interval_timer++ >= 30){key_continue_flag = 0;key_interval_timer = 0;if (key_clik_cnt == 1){key_clik_cnt = 0;event_set_ui(EVENT_UI_KEY_CLICK);printf("Key single click\r\n");}else if (key_clik_cnt == 2){key_clik_cnt = 0;event_set_ui(EVENT_UI_DOUBLE_CLICK);printf("Key double click\r\n");}else if (key_clik_cnt == 3){key_clik_cnt = 0;event_set_ui(EVENT_UI_TRIPLE_CLICK);printf("Key triple click\r\n");} }}else{key_interval_timer = 0;key_clik_cnt = 0;}if (key_0_pressed_cnt > CONFIG_KEY_2S_PRESS_CNT){event_set_ui(EVENT_UI_KEY_TWS_PAR_PRESS);key_0_pressed_cnt = 0;printf("Key long hold\r\n");}
}
按键组合动作识别
待补充…