在我们平时的嵌入式开发应用中,有时候需要使用单个按键实现单击,双击,长按等多种功能,这样可以在资源紧缺的开发板上用单个按键实现多种功能,比如GUI 图像的切换,音量的快速增减等等,非常的使用。单个按键实现单击,双击,长按是非常有必要的。
打开原理图,我们可以看到按键SW1电路图如下:

按键SW1对应的IO口是P005

串口对应的IO口分别是 P109 和 P110
本次测试我主要演示按键单击,双击,长按时实现的功能,每种功能通过串口打印出来。
先上干货。
打开之前我们建立好的串口工程,


串口功能测试正常
接下来我们配置按键SW1对应的P005
在keil里打开Smart Configurator
将P005设为输入模式


#include "hal_data.h"
#include "stdio.h"
#include <stdbool.h>
#include "multi_button.h"
以下是按键处理函数
void BTN1_PRESS_DOWN_Handler(void* btn);
void BTN1_PRESS_UP_Handler(void* btn);
void BTN1_PRESS_REPEAT_Handler(void* btn);
void BTN1_SINGLE_Click_Handler(void* btn);
void BTN1_DOUBLE_Click_Handler(void* btn);
void BTN1_LONG_PRESS_START_Handler(void* btn);
void BTN1_LONG_PRESS_HOLD_Handler(void* btn);
#define s1 BSP_IO_PORT_00_PIN_05
#define s1_down 0
#define s1_up 1
#define s1_Double_click 0
#define s1_NoDouble_click 1
uint32_t btncnt = 0;
static uint8_t read_key(void)
{
bsp_io_level_t S1;
R_IOPORT_PinRead(&g_ioport_ctrl,s1,&S1);
if(S1 == BSP_IO_LEVEL_LOW) return s1_down;
else return s1_up;
}
enum Button_IDs {
btn1_id,
btn2_id,
};
struct Button btn1;
struct Button btn2;
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 read_key();
default:
return 0;
}
}


主函数里添加
button_init(&btn1, read_button_GPIO, 0, btn1_id);
button_attach(&btn1, PRESS_DOWN, BTN1_PRESS_DOWN_Handler);
// button_attach(&btn1, PRESS_UP, BTN1_PRESS_UP_Handler);
// button_attach(&btn1, PRESS_REPEAT, BTN1_PRESS_REPEAT_Handler);
// button_attach(&btn1, SINGLE_CLICK, BTN1_SINGLE_Click_Handler);
// button_attach(&btn1, DOUBLE_CLICK, BTN1_DOUBLE_Click_Handler);
// button_attach(&btn1, LONG_PRESS_START, BTN1_LONG_PRESS_START_Handler);
button_attach(&btn1, LONG_PRESS_HOLD, BTN1_LONG_PRESS_HOLD_Handler);
button_start(&btn1);
while(1)
{
button_ticks();
R_BSP_SoftwareDelay(5, BSP_DELAY_UNITS_MILLISECONDS); // 延时5ms
}

void BTN1_PRESS_DOWN_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
btncnt++;
printf("按键次数为 %d\r\n", btncnt);
}
void BTN1_PRESS_UP_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
}
void BTN1_PRESS_REPEAT_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
}
void BTN1_SINGLE_Click_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
}
void BTN1_DOUBLE_Click_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
}
void BTN1_LONG_PRESS_START_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
}
void BTN1_LONG_PRESS_HOLD_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
btncnt--;
printf("按键次数为 %d\r\n", btncnt);
}


我在
void BTN1_PRESS_DOWN_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
btncnt++;
printf("按键次数为 %d\r\n", btncnt);
}
实现了单击按键
按键次数加一
void BTN1_LONG_PRESS_HOLD_Handler(void* btn)
{
printf("%s\r\n", FUNCTION);
btncnt--;
printf("按键次数为 %d\r\n", btncnt);
}
中实现了长按按键,按键次数减一
烧录程序,打开串口助手观察效果


结论正确,请看视频