bouton_isr.c

ESP32-H2 · File : bouton_isr.c · Language : C · Use case : Réagir à un bouton par interruption GPIO

In ESP-IDF a button is watched by interrupt: the ISR fires on the edge, the task prints. IRAM_ATTR is mandatory because flash may be unavailable during the interrupt.

Hardware required

An ESP32-H2 board (RISC-V 96 MHz, IEEE 802.15.4 radio only — no Wi-Fi) such as a DevKitM-1, powered over USB. 1 push button to GND (GPIO9 doubles as BOOT: short presses fine).

Wiring

Button between GPIO9 and GND; the pull-up is enabled in gpio_config. Any GPIO-matrix pin works.

How it works

gpio_config arms the falling-edge interrupt; the ISR only increments a volatile counter (golden rule: short ISR). The task compares and prints at 20 Hz, filtering bounce. Program it with ESP-IDF (idf.py set-target esp32h2); the USB-Serial/JTAG port (GPIO26/27) acts as console and flash port. Hold Boot + Reset for download mode if needed.

Going further

Wake the SoC with the same interrupt (esp_sleep_enable_ext0_wakeup) for a battery-powered detector.

bouton_isr.c

// bouton_isr.c — interruption sur front, compte les appuis.
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"

#define BROCHE 9                    // bouton vers GND (GPIO9 = BOOT du DevKit)
static volatile int appuis = 0;
static const char *TAG = "bouton";

static void IRAM_ATTR sur_appui(void *arg)
{
    appuis++;                       // le minimum en contexte d'ISR
}

void app_main(void)
{
    gpio_config_t io = {
        .pin_bit_mask = 1ULL << BROCHE,
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,
        .intr_type = GPIO_INTR_NEGEDGE,   // front descendant = appui
    };
    gpio_config(&io);
    gpio_install_isr_service(0);
    gpio_isr_handler_add(BROCHE, sur_appui, NULL);

    int vu = 0;
    while (1) {
        if (vu != appuis) { vu = appuis; ESP_LOGI(TAG, "appui n°%d", vu); }
        vTaskDelay(pdMS_TO_TICKS(50));   // anti-rebond par echantillonnage
    }
}

← Back to the board