ESP-IDFESP32 DevKit V1Lab virtual

ESP-IDF: button interrupt and a queue

An interrupt handler feeds a FreeRTOS queue; a task counts the presses and toggles GPIO2.

ESP-IDF: button interrupt and a queue in Argynix Lab

The code

main.cC
/* A button's interrupt feeds a FreeRTOS queue, as ESP-IDF's generic_gpio example: the
   interrupt handler only sends the pin number; a task takes it from the queue,
   counts the presses and toggles the LED on GPIO2. The button is on GPIO4, to GND. */
#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "esp_log.h"

#define LED_GPIO GPIO_NUM_2
#define BUTTON_GPIO GPIO_NUM_4

static const char *TAG = "gpio";
static QueueHandle_t 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 button_task(void *arg)
{
    uint32_t io_num;
    int presses = 0;
    for (;;) {
        if (xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {
            presses++;
            gpio_set_level(LED_GPIO, presses & 1);
            ESP_LOGI(TAG, "GPIO[%" PRIu32 "] interrupt, press %d, LED %s", io_num, presses, presses & 1 ? "on" : "off");
        }
    }
}

void app_main(void)
{
    gpio_config_t led = {
        .pin_bit_mask = 1ULL << LED_GPIO,
        .mode = GPIO_MODE_OUTPUT,
    };
    gpio_config(&led);

    gpio_config_t button = {
        .pin_bit_mask = 1ULL << BUTTON_GPIO,
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,
        .intr_type = GPIO_INTR_NEGEDGE,
    };
    gpio_config(&button);

    gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
    xTaskCreate(button_task, "button_task", 2048, NULL, 10, NULL);

    gpio_install_isr_service(0);
    gpio_isr_handler_add(BUTTON_GPIO, gpio_isr_handler, (void *)BUTTON_GPIO);

    ESP_LOGI(TAG, "Press the button on GPIO%d", BUTTON_GPIO);
    for (;;) {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}