之前本来以为是一个非常容易的例程。结果闹了很多乌龙。
首先,ESP32官方提供了一个按键例程。需要使用到components文件。然后添加这个文件需要一点讲究。不然就会报出下面这个错误:
所以,第一步:需要将components文件夹复制到工程文件夹下面,要特别注意复制的位置。
同时需要在工程的CmakeLists中添加编译路径,特别注意,不是在main文件夹下的CmakeLists中添加。
至此,即可将官方提供的按键驱动添加到工程中使用。
使用也很简单。源码如下图所示:
#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_log.h"
#include "iot_button.h"
#define LIGHT_BUTTON_GPIO 9 /* This is the button that is used for toggling the output */
#define LIGHT_BUTTON_ACTIVE_LEVEL 0
static void push_btn_cb(void *arg)
{
printf("按键被按下!\n");
}
void key_driver_init(void)
{
/* Configure push button */
button_config_t btn_cfg = {
.type = BUTTON_TYPE_GPIO,
.gpio_button_config = {
.gpio_num = LIGHT_BUTTON_GPIO,
.active_level = LIGHT_BUTTON_ACTIVE_LEVEL,
},
};
button_handle_t btn_handle = iot_button_create(&btn_cfg);
if (btn_handle) {
/* Register a callback for a button short press event */
iot_button_register_cb(btn_handle, BUTTON_LONG_PRESS_START, push_btn_cb);
}
}
void app_main(void)
{
key_driver_init();
while(1){
printf("system run ...\n");
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
其中iot_button_register_cb(btn_handle, BUTTON_LONG_PRESS_START, push_btn_cb);可以设置按键的触发方式。
typedef enum {
BUTTON_PRESS_DOWN = 0,
BUTTON_PRESS_UP,
BUTTON_PRESS_REPEAT,
BUTTON_SINGLE_CLICK,
BUTTON_DOUBLE_CLICK,
BUTTON_LONG_PRESS_START,
BUTTON_LONG_PRESS_HOLD,
BUTTON_EVENT_MAX,
BUTTON_NONE_PRESS,
} button_event_t;
在这个例程中,我选择了单次长按触发方式。其他的触发方式验证也可使用。
运行示例如下图所示: