概述
在实际项目中,经常需要用到独立按键来作为人机交互的工具。为了避免重复造轮子,这里简单介绍一个使用组件FlexibleButton的移植,它支持单击、双击、长按等常用事件。
正文
废话不多说,直接开盘。
第一步:获取源码
链接
第二步:准备好工程,并把源文件加入工程。
第三步:注册按键
参考代码如下:
static flex_button_t user_button[1];
static void flex_key_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
static uint8_t button_key0_read(void)
{
return GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
}
static void btn_0_cb(flex_button_t *btn)
{
char_device_t *uart_dev = NULL;
uart_dev = char_device_find("uart");
switch (btn->event)
{
case FLEX_BTN_PRESS_DOWN:
uart_dev->dops->write("key down\r\n", 10);
break;
case FLEX_BTN_PRESS_CLICK:
uart_dev->dops->write("key click\r\n", 11);
break;
case FLEX_BTN_PRESS_DOUBLE_CLICK:
uart_dev->dops->write("key dclick\r\n", 12);
break;
case FLEX_BTN_PRESS_SHORT_START:
uart_dev->dops->write("key short\r\n", 11);
break;
case FLEX_BTN_PRESS_SHORT_UP:
uart_dev->dops->write("key shortup\r\n", 13);
break;
case FLEX_BTN_PRESS_LONG_START:
uart_dev->dops->write("key long\r\n", 10);
break;
case FLEX_BTN_PRESS_LONG_UP:
uart_dev->dops->write("key longup\r\n", 12);
break;
case FLEX_BTN_PRESS_LONG_HOLD:
uart_dev->dops->write("key longhold\r\n", 14);
break;
case FLEX_BTN_PRESS_LONG_HOLD_UP:
uart_dev->dops->write("key longholdup\r\n", 16);
break;
case FLEX_BTN_PRESS_REPEAT:
uart_dev->dops->write("key repeat\r\n", 12);
break;
}
}
static void flex_key_struct_init(void)
{
flex_key_init();
rt_memset(&user_button[0], 0x0, sizeof(user_button));
user_button[0].usr_button_read = button_key0_read;
user_button[0].cb = (flex_button_response_callback)btn_0_cb;
user_button[0].status = 0;
user_button[0].pressed_logic_level = 1;
user_button[0].click_start_tick = 20;
user_button[0].short_press_start_tick = 100;
user_button[0].long_press_start_tick = 200;
user_button[0].long_hold_start_tick = 300;
user_button[0].repeat_interval_tick = 20;
flex_button_register(&user_button[0]);
}
void KEYthread_entry(void *para)
{
flex_key_struct_init();
while(1)
{
flex_button_scan();
rt_thread_mdelay(10);
}
}
第四步:修改源码
由于原版源码不支持按键长按连发功能,所以简单修改,以增加按键连发功能。 修改代码如下:
static void flex_button_process(void)
{
......
case 5:
if (!(cont & (1 << i)))
{
target->status = 2;
}
else if (target->scan_cnt >= target->long_hold_start_tick)
{
target->status = 6;
repeat_cnt = 0;
target->event = FLEX_BTN_PRESS_LONG_HOLD;
EVENT_CB_EXECUTOR(target);
}
break;
case 6:
if (!(cont & (1 << i)))
{
target->status = 2;
}
else
{
if(++repeat_cnt >= target->repeat_interval_tick)
{
repeat_cnt = 0;
target->event = FLEX_BTN_PRESS_REPEAT;
EVENT_CB_EXECUTOR(target);
}
}
break;
}
第五步:调试接口
效果展示如下:
总结
这样就完成了FlexibleButton的移植工作。
|