之前的文章中介绍过按键的处理方法《多功能(单击、双击、长按)按键设计》,今天再来分享另外一种方式:MultiButton。
1.Multi_Button简介
MultiButton 是Github上的一个开源的按键处理组件,作者0x1abin。
GIthub地址:https://github.com/0x1abin/MultiButton
MultiButton一个小巧简单易用的事件驱动型按键驱动模块,可无限量扩展按键,按键事件的回调异步处理方式可以简化你的程序结构,去除冗余的按键处理硬编码,让你的按键业务逻辑更清晰。
2.Multi_Button的使用
模块只有两个文件multi_button.c和multi_button.h,使用时,将.c文件添加到工程中。这里以STM32为例。
Button button1;
Button button2;
uint8_t read_button_GPIO(uint8_t button_id)
{
// you can share the GPIO read function with multiple Buttons
switch(button_id)
{
case btn1_id:
return HAL_GPIO_ReadPin(KEY0_GPIO_Port, KEY0_Pin);
break;
case btn2_id:
return HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin);
break;
default:
return 0;
break;
}
}
button_init(&button1, read_button_GPIO, 0, btn1_id);
button_init(&button2, read_button_GPIO, 0, btn2_id);
button_attach(&button1, PRESS_DOWN, BTN_PRESS_DOWN_Handler);
button_attach(&button1, PRESS_UP, BTN_PRESS_UP_Handler);
button_attach(&button1, PRESS_REPEAT, BTN_PRESS_REPEAT_Handler);
button_attach(&button1, SINGLE_CLICK, BTN_SINGLE_Click_Handler);
button_attach(&button1, DOUBLE_CLICK, BTN_DOUBLE_Click_Handler);
button_attach(&button1, LONG_PRESS_START, BTN_LONG_PRESS_START_Handler);
button_attach(&button1, LONG_PRESS_HOLD, BTN_LONG_PRESS_HOLD_Handler);
button_attach(&button2, PRESS_DOWN, BTN_PRESS_DOWN_Handler);
button_attach(&button2, PRESS_UP, BTN_PRESS_UP_Handler);
button_attach(&button2, PRESS_REPEAT, BTN_PRESS_REPEAT_Handler);
button_attach(&button2, SINGLE_CLICK, BTN_SINGLE_Click_Handler);
button_attach(&button2, DOUBLE_CLICK, BTN_DOUBLE_Click_Handler);
button_attach(&button2, LONG_PRESS_START, BTN_LONG_PRESS_START_Handler);
button_attach(&button2, LONG_PRESS_HOLD, BTN_LONG_PRESS_HOLD_Handler);
这里绑定了所有的按键功能,用户可根据实际需求进行删减。不同的按键回调函数可以相同,以按键按下的回调函数为例,函数如下:
void BTN_PRESS_DOWN_Handler(void* btn)
{
Button *temp_button = (Button *)btn;
switch(temp_button->button_id)
{
case btn1_id:
printf("btn1 press downrn");
break;
case btn2_id:
printf("btn2 press downrn");
break;
default:
break;
}
}
button_start(&button1);
button_start(&button2);
void scan_key()
{
if(key_tick < TICKS_INTERVAL)return;
key_tick = 0;
button_ticks();
}
//According to your need to modify the constants.
测试工程链接:
链接:https://pan.baidu.com/s/1wiw5Ajoooc7WZFgwO87zqw
提取码:wola
文章评论