MultiButton移植记录

使用记录

使用PA0引脚,电路图如下,使用GPIO内部下拉。
image

实际测试,很稳定,没有误触发,单击、双击、长按很稳定。
image

移植记录

  1. 复制multi_button.c和multi_button.h到工程中,实现GPIO的初始化、读取。
void key_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    /* GPIO Ports Clock Enable */
    __HAL_RCC_GPIOA_CLK_ENABLE();
    /*Configure GPIO pin : KEY_WK_UP_Pin */
    GPIO_InitStruct.Pin = KEY_WK_UP_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLDOWN;
    HAL_GPIO_Init(KEY_WK_UP_GPIO_Port, &GPIO_InitStruct);
}
/// multi_button 移植接口
uint8_t read_button_gpio(uint8_t button_id)
{
    switch (button_id)
    {
        case 1:
            return HAL_GPIO_ReadPin(KEY_WK_UP_GPIO_Port, KEY_WK_UP_Pin);
            break;
        default:
            return 0;
    }
}
  1. 实现定时器回调,button_ticks()函数需要5ms调用一次,自己实现定时器中断,5ms中断一次。或者使用软件定时器。
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance == TIM6)
	{
		button_ticks();
	}
}

调整下面参数,可以调整短按、长按的时间间隔

// Configuration constants - can be modified according to your needs
#define TICKS_INTERVAL          5    // ms - timer interrupt interval
#define DEBOUNCE_TICKS          3    // MAX 7 (0 ~ 7) - debounce filter depth
#define SHORT_TICKS             (300 / TICKS_INTERVAL)   // short press threshold
#define LONG_TICKS              (1000 / TICKS_INTERVAL)  // long press threshold
#define PRESS_REPEAT_MAX_NUM    15   // maximum repeat counter value
  1. 使用MultiButton
void key_wkup_single_click_handle(Button *btn)
{
	static uint32_t cnt = 1;
	printf("key_wkup: Single Click,cnt = %d\n",cnt);
	cnt++;
}
void key_wkup_double_click_handle(Button *btn)
{
	static uint32_t cnt = 1;
	printf("key_wkup: Double Click,cnt = %d\n",cnt);
	cnt++;	
}
void key_wkup_long_press_handle(Button *btn)
{
	printf("key_wkup: long press\n");
}

int main(void)
{
    //初始化按键,active_level:0:低电平有效,1:高电平有效
	button_init(&key_wkup,read_button_gpio,1,1);
	//注册单击事件回调
	button_attach(&key_wkup,BTN_SINGLE_CLICK,key_wkup_single_click_handle);
	//注册双击事件回调
	button_attach(&key_wkup,BTN_DOUBLE_CLICK,key_wkup_double_click_handle);
	//注册长按事件回调
	button_attach(&key_wkup,BTN_LONG_PRESS_START,key_wkup_long_press_handle);
	//启动按键处理
	button_start(&key_wkup);
    while(1)
    {
        ///process other things
    }

    
}

轮询方式
裸机下的思路:
假如有四个按键,先注册好4个按键的各个回调函数,比如每个按键的单击、双击、长按等,然后在回调函数中,入队,也就是每个按键的状态入队,最后在轮询中查询队列是否为非空,如果非空,就表示有按键的事件,否则就表示没有按键事件。
需要写一个环形队列(FIFO)
RTOS下的思路:
和裸机思路一样,不过使用RTOS自带的队列,更方便的使用了。

参考资料:
开源链接: GitHub仓库

posted @ 2025-12-07 12:30  早点睡0001  阅读(4)  评论(0)    收藏  举报