陈拓 2022/06/19-2022/06/19
1. 概述
- 此示例显示了如何配置GPIO以及如何在中断时使用它。
- 引脚功能
开发板上只有一个按键接在GPIO0。该引脚在烧固件时需要拉低,程序运行时作为普通按钮输入。
- 官方例程国内镜像
https://gitee.com/EspressifSystems/esp-idf/tree/master/examples/peripherals/gpio/generic_gpio
2. 开发环境
《用乐鑫国内Gitee镜像搭建ESP32开发环境》
https://zhuanlan.zhihu.com/p/348106034
https://blog.csdn.net/chentuo2000/article/details/113424934?spm=1001.2014.3001.5501
3. 修改代码
因为我们只有一个按键接在PGIO0上,修改代码用中断方式捕捉按键按下和松开,对应下降沿和上升沿中断。
gpio_example_main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
/**
* Brief:
* This test code shows how to configure gpio and how to use gpio interrupt.
*
* GPIO0: input, pulled up, interrupt from rising edge and falling edge
*
*/
#define GPIO_INPUT_IO_0 0
#define GPIO_INPUT_PIN_SEL 1ULL<<GPIO_INPUT_IO_0
#define ESP_INTR_FLAG_DEFAULT 0
static xQueueHandle gpio_evt_queue = NULL;
static void IRAM_ATTR gpio_isr_handler(void* arg)
{
uint32_t gpio_num = (uint32_t) arg;
xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
}
static void gpio_task_example(void* arg)
{
uint32_t io_num;
for(;;) {
if(xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {
printf("GPIO[%d] intr, val: %d\n", io_num, gpio_get_level(io_num));
}
}
}
void app_main(void)
{
gpio_config_t io_conf = {}; //zero-initialize the config structure.
//io_conf.intr_type = GPIO_INTR_POSEDGE; // 上升沿产生中断
io_conf.intr_type = GPIO_INTR_ANYEDGE; // 上升、下降沿都产生中断
io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; //bit mask of the pins, use GPIO0 here
io_conf.mode = GPIO_MODE_INPUT; //set as input mode
io_conf.pull_up_en = 1; //enable pull-up mode
gpio_config(&io_conf);
//create a queue to handle gpio event from isr
gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
//start gpio task
xTaskCreate(gpio_task_example, "gpio_task_example", 2048, NULL, 10, NULL);
//install gpio isr service
gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
//hook isr handler for specific gpio pin
gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0);
printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());
}
4. 构建项目
- 刷新esp-idf环境
get_idf
- 设定目标芯片
idf.py set-target esp32
- 配置项目
idf.py menuconfig
1) 将闪存设置为4MB
保存,退出。
- 编译项目
idf.py build
- 烧写项目
查看USB转串口的COM口号:
烧写:
idf.py -p /dev/ttyS3 -b 115200 flash
- 启用监视器
idf.py monitor -p /dev/ttyS3
(Ctrl+]可以退出监视器程序)
按键按下是下降沿值为0,按键松开是上升沿值为1.