Skip to content
systemcoding.dev
Embedded

Configure ESP32 GPIO With gpio_config and Pin Interrupts

Configure ESP32 outputs and a button input with gpio_config in ESP-IDF 5.x, then add a falling-edge interrupt with gpio_install_isr_service and a queue.

7 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Espressif, Arm and C logos.

ESP-IDF configures GPIO through one structure and one function: gpio_config_t describes a set of pins and what they should do, and gpio_config() applies it. The same structure covers the direction, the pull resistors and the interrupt type, so a button with an interrupt is a handful of lines. This post sets up an LED output and a button input on an ESP32 dev board using ESP-IDF 5.3, then adds a falling-edge interrupt that sends events to a FreeRTOS task through a queue. It explains the rule that decides what an interrupt service routine may call, which is where first attempts usually go wrong. Pin choices avoid the strapping and flash pins, which a later post in this cluster covers.

The configuration structure

gpio_config_t has five fields, defined in driver/gpio.h:

FieldTypeMeaning
pin_bit_maskuint64_tOne bit per GPIO number to configure; several pins at once
modegpio_mode_tGPIO_MODE_INPUT, GPIO_MODE_OUTPUT, GPIO_MODE_OUTPUT_OD, GPIO_MODE_INPUT_OUTPUT and so on
pull_up_engpio_pullup_tGPIO_PULLUP_ENABLE or GPIO_PULLUP_DISABLE
pull_down_engpio_pulldown_tGPIO_PULLDOWN_ENABLE or GPIO_PULLDOWN_DISABLE
intr_typegpio_int_type_tGPIO_INTR_DISABLE, GPIO_INTR_POSEDGE, GPIO_INTR_NEGEDGE, GPIO_INTR_ANYEDGE, GPIO_INTR_LOW_LEVEL, GPIO_INTR_HIGH_LEVEL

The mask is a 64-bit value built with 1ULL << pin. The ULL matters: 1 << 32 on a 32-bit int overflows for pins above 31, and the ESP32 has GPIOs up to 39. The function returns ESP_OK or an error such as ESP_ERR_INVALID_ARG.

Output and input

An LED on GPIO 2 (the on-board LED of many ESP32 DevKit boards, though GPIO 2 is a strapping pin, which later posts discuss) and a button on GPIO 4 to ground:

gpio_basic.cc
#include "driver/gpio.h"
#include "esp_err.h"

#define LED_GPIO    GPIO_NUM_2
#define BUTTON_GPIO GPIO_NUM_4

void gpio_setup(void)
{
	gpio_config_t led = {
		.pin_bit_mask = 1ULL << LED_GPIO,
		.mode = GPIO_MODE_OUTPUT,
		.pull_up_en = GPIO_PULLUP_DISABLE,
		.pull_down_en = GPIO_PULLDOWN_DISABLE,
		.intr_type = GPIO_INTR_DISABLE,
	};
	ESP_ERROR_CHECK(gpio_config(&led));

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

Output and read use two simple calls:

c
gpio_set_level(LED_GPIO, 1);                 /* drive high */
int pressed = !gpio_get_level(BUTTON_GPIO);  /* active low with the pull-up */

gpio_set_level(gpio, level) writes 0 or 1. gpio_get_level(gpio) returns the pin level, 0 or 1. The button is active low, as in any pull-up wiring.

The structure must be fully initialised. Designated initialisers set the unnamed fields to zero, which is correct for this structure (zero means disable and no interrupt), but a gpio_config_t on the stack declared without an initialiser contains garbage and produces unpredictable behaviour.

Adding the interrupt

An interrupt-driven button needs three things: the interrupt type in the configuration, the GPIO ISR service installed once, and a handler added for the pin.

gpio_isr.cc
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"

#define BUTTON_GPIO GPIO_NUM_4

static const char *TAG = "button";
static QueueHandle_t button_queue;

static void IRAM_ATTR button_isr(void *arg)
{
	uint32_t gpio_num = (uint32_t)arg;

	xQueueSendFromISR(button_queue, &gpio_num, NULL);
}

static void button_task(void *arg)
{
	uint32_t gpio_num;

	for (;;) {
		if (xQueueReceive(button_queue, &gpio_num, portMAX_DELAY))
			ESP_LOGI(TAG, "GPIO %lu falling edge", (unsigned long)gpio_num);
	}
}

void button_irq_setup(void)
{
	gpio_config_t cfg = {
		.pin_bit_mask = 1ULL << BUTTON_GPIO,
		.mode = GPIO_MODE_INPUT,
		.pull_up_en = GPIO_PULLUP_ENABLE,
		.pull_down_en = GPIO_PULLDOWN_DISABLE,
		.intr_type = GPIO_INTR_NEGEDGE,
	};
	ESP_ERROR_CHECK(gpio_config(&cfg));

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

	ESP_ERROR_CHECK(gpio_install_isr_service(0));
	ESP_ERROR_CHECK(gpio_isr_handler_add(BUTTON_GPIO, button_isr, (void *)BUTTON_GPIO));
}

gpio_install_isr_service(intr_alloc_flags) installs the shared GPIO interrupt handler once, with 0 meaning default allocation flags. Calling it twice returns ESP_ERR_INVALID_STATE, so install it from one place. gpio_isr_handler_add(gpio, handler, arg) registers a per-pin function; arg is passed to it. The driver's central ISR reads which pins fired and calls each registered handler.

On a press, with the button wired to ground:

Text
I (10532) button: GPIO 4 falling edge
I (10781) button: GPIO 4 falling edge

The timestamps are an example. Without debouncing, one physical press of a switch can produce several lines because the contacts bounce, and each bounce is a falling edge.

What an ISR may call

The handler runs in interrupt context, and the rules differ from a task:

  • **Mark it IRAM_ATTR.** The function must be in internal RAM so it can run while the flash cache is disabled, for example during a flash write. A handler in flash that fires then crashes the chip with a cache error. The attribute IRAM_ATTR places the function in IRAM; any function it calls must be in IRAM too, or inlined, or in ROM.

  • **Call only the FromISR variants of FreeRTOS functions.** xQueueSendFromISR is correct; xQueueSend would use a blocking path that is invalid in an ISR. The third argument, NULL here, is a pointer to a BaseType_t that tells whether a higher-priority task was woken; for a correct handler, use it and request a context switch on exit:

c
static void IRAM_ATTR button_isr(void *arg)
{
	uint32_t gpio_num = (uint32_t)arg;
	BaseType_t woken = pdFALSE;

	xQueueSendFromISR(button_queue, &gpio_num, &woken);
	if (woken)
		portYIELD_FROM_ISR();
}
  • Do not log or call anything that blocks. ESP_LOGI takes locks and uses the flash-resident format strings; the handler passes the work to a task, which logs.

  • Keep it short. The handler sends the pin number and returns. All the policy, such as debouncing and deciding what the press means, lives in the task.

The reason for the task-and-queue structure is that the ISR cannot do much, and the queue carries the event across.

Ways it goes wrong

Crash on first interrupt: "Cache disabled but cached memory region accessed". The handler or a function it calls is not in IRAM. Add IRAM_ATTR to the handler and avoid calls into flash code such as printf.

No interrupts arrive. The ISR service was not installed, or gpio_isr_handler_add was called before gpio_install_isr_service, or the intr_type is GPIO_INTR_DISABLE. Check the return codes; the ESP_ERROR_CHECK macro aborts with the error name.

Interrupts fire constantly. A level-triggered interrupt (GPIO_INTR_LOW_LEVEL) fires repeatedly while the pin stays low. Use an edge type for buttons.

Pins above 33 as outputs. GPIOs 34 to 39 on the ESP32 are input-only and have no pull-up or pull-down resistors. gpio_config with output mode on them fails or does nothing.

Pull-ups on a wake-up pin. If the pin is also used as a deep-sleep wake source, the RTC domain controls its pull; see the sleep documentation.

Reading the configuration back

When a pin does not behave, ask the driver what it was configured to do. ESP-IDF 5.x can print the state of any set of pins:

c
gpio_dump_io_configuration(stdout, 1ULL << BUTTON_GPIO);

The dump lists the pull-up and pull-down state, the input and output enables, whether the pin is open-drain and which function the IO MUX has selected. A button pin that reports Pullup: 0 means the pull_up_en field was not applied, usually because the structure was filled after the gpio_config call or an input-only pin was used. A pin that reports a function other than GPIO means another driver, such as a UART or SPI initialisation, claimed it after your setup: the last driver to configure a pin wins, so check the order of the initialisation calls.

For the interrupt, gpio_intr_disable(gpio) and gpio_intr_enable(gpio) pause and resume one pin without removing its handler, which is useful while a debounce timer runs: disable in the handler after the first edge, re-enable from the timer callback once the contact has settled.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.