GPIO, timers and interrupts
Read a button and blink an LED without blocking: GPIO pull-ups, interrupts that do almost nothing, debouncing by quiet time, and timers in ESP-IDF, Arduino and the Pico SDK.
You will learn
- Explain why delay() blocks a superloop and what to use instead
- Configure a GPIO input with a pull-up and an edge interrupt
- Write an interrupt handler that only records the event
- Debounce a mechanical button by waiting for a quiet period
- Drive periodic work from a timer instead of a delay
This lesson turns the blinking LED from lesson 3 into a program that does two things at once: it blinks, and it reacts to a button. That small step is where most beginners meet the three tools every IoT device depends on: GPIO (general-purpose input and output) pins, interrupts and timers. The examples use the ESP32-C5-DevKitC-1’s own Boot button, so you need no extra parts. A Raspberry Pi Pico 2 W version in C follows, with one wire and a push button.
Why delay() hurts
The lesson 3 programs end each loop with delay(500) or vTaskDelay. While the program waits there, it does nothing else. Add a button check to the same loop, as below, and the pin is looked at once a second. A press shorter than that can fall entirely inside the two waits and be missed, and a longer one is noticed up to a second late.
// target: esp32c5 sdk: arduino-esp32 tier: 1
// The blocking version, for comparison only: presses during either delay() are missed.
void setup() {
pinMode(28, INPUT_PULLUP); // Boot button, pressed = LOW
}
void loop() {
rgbLedWrite(RGB_BUILTIN, 0, 0, 16);
delay(500); // a press now is not seen
rgbLedWrite(RGB_BUILTIN, 0, 0, 0);
delay(500); // nor now
if (digitalRead(28) == LOW) {
rgbLedWrite(RGB_BUILTIN, 16, 0, 0); // only reached once per second
}
}
Two fixes run through the rest of this lesson. First, let the hardware tell you when the pin changes, with an interrupt, instead of looking at it now and then. Second, replace “wait 500 ms” with “has 500 ms passed yet?”, either by comparing timestamps or by giving the work to a timer. Then the loop never stops, and every job gets checked thousands of times a second.
Reading a button
A button connects a pin to ground when pressed. When it is released, nothing drives the pin, so it floats and reads random values. A pull-up resistor fixes that by holding the pin at the supply voltage until the button pulls it low. The ESP32-C5 has an internal weak pull-up of 45 kΩ (typical, at 3.3 V and 25 °C), enough for a button on a short wire.
On the DevKitC-1 the Boot button (SW1 on the v1.2 schematic) shorts GPIO28 to ground. GPIO28 also has the chip’s pull-up enabled at reset, because it is a strapping pin that selects normal boot when high. After the program starts, the pin is free to use as an input, which makes the Boot button a handy test button. Hold it during a reset, though, and the chip enters download mode instead of running your code. The schematic shows a 0.1 µF capacitor position across the button, C13, marked “NC” (not fitted), so the board does no hardware debouncing. Your firmware has to.
Interrupts: record, then leave
An interrupt makes the CPU stop what it is doing and run a short function, the ISR (interrupt service routine), when a hardware event happens, such as an edge on a pin. Three rules keep ISRs safe:
- Do as little as possible: record the event, perhaps a timestamp, and wake the code that will handle it.
- Never wait, print or allocate memory inside one. Those can block, and a blocked ISR stalls the whole system.
- Mark variables shared between the ISR and normal code
volatile, so the compiler re-reads them every time.
In ESP-IDF the ISR sends a message to a FreeRTOS queue with xQueueSendFromISR, the variant that is safe in interrupt context, and a task does the real work. In Arduino and the Pico SDK the ISR sets a flag that the loop checks.
Bouncing contacts
A mechanical switch does not close cleanly. The contacts touch, separate and touch again several times before they settle, so one press can produce a burst of edges. Counting edges counts bounces, not presses.
The examples below use the quiet-time method. Every edge restarts a 20 ms window. Once the pin has been quiet for the whole window, the code reads it once and compares the result with the last stable state. The 20 ms value is our choice for typical tactile switches, not a figure from a datasheet. The firmware prints how many raw edges each press produced, so you can see how much your own button bounces and shorten or lengthen the window.
Timers
A timer runs code at a set time or period without a loop waiting for it. Three kinds appear in the examples.
- esp_timer (ESP-IDF). Espressif’s high-resolution timer counts in microseconds. By default its callbacks run one after another in a dedicated high-priority task, so Espressif advises keeping them short. Our blink callback writes one LED and returns.
esp_timer_restart()changes the period of a running timer, which is how a button press changes the blink rate. - FreeRTOS delays.
vTaskDelay()counts in scheduler ticks. ESP-IDF v6.1.1 sets the tick rate to 100 Hz by default, so delays come in 10 ms steps. ThepdMS_TO_TICKS()macro rounds down, and the first tick of a delay may already be partly over, so FreeRTOS only promises the delay to within one tick. The examples add one tick wherever a minimum time matters. Ticks are fine for “let the contacts settle” and wrong for timing anything shorter than a few ticks. - Timestamps (Arduino and Pico SDK).
millis()andtime_us_32()return a counter. The patternif (now - last >= period)with unsigned numbers keeps working when the counter wraps round to zero, whichmillis()does after 232 milliseconds.
The ESP-IDF version
// target: esp32c5 sdk: esp-idf tier: 1
// GPIO interrupt, debounce and a periodic timer on the ESP32-C5-DevKitC-1.
// The Boot button (SW1) shorts GPIO28 to ground. Each debounced press changes
// the blink period of the RGB LED, which a periodic esp_timer drives, so the
// blinking never waits for the button code and the button never waits for the LED.
#include <inttypes.h>
#include <stdio.h>
#include "driver/gpio.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "led_strip.h"
#define BUTTON_GPIO 28 // Boot button: pressed = low (board schematic v1.2)
#define RGB_LED_GPIO 27 // addressable RGB LED (board user guide)
#define DEBOUNCE_MS 20 // wait this long after the last edge, then read the pin
static QueueHandle_t edge_queue;
static volatile uint32_t raw_edges; // every edge the ISR saw, bounces included
static led_strip_handle_t led;
static esp_timer_handle_t blink_timer;
static const uint64_t periods_us[] = {1000000, 500000, 250000, 125000};
// Keep the ISR short: count the edge and wake the task. No printf, no delays.
static void IRAM_ATTR button_isr(void *arg)
{
raw_edges++;
uint32_t dummy = 0;
BaseType_t woken = pdFALSE;
xQueueSendFromISR(edge_queue, &dummy, &woken); // drops the event if the queue is full
if (woken) {
portYIELD_FROM_ISR();
}
}
// Runs in the esp_timer task every period, independent of the button logic.
static void blink_cb(void *arg)
{
static bool on;
on = !on;
if (on) {
led_strip_set_pixel(led, 0, 0, 0, 16); // dim blue
led_strip_refresh(led);
} else {
led_strip_clear(led);
}
}
static void button_task(void *arg)
{
int stable = gpio_get_level(BUTTON_GPIO); // 1 = released
uint32_t presses = 0, seen = 0, dummy;
size_t speed = 0;
for (;;) {
xQueueReceive(edge_queue, &dummy, portMAX_DELAY); // sleep until an edge
vTaskDelay(pdMS_TO_TICKS(DEBOUNCE_MS) + 1); // settle: +1 tick so it is never short
xQueueReset(edge_queue); // forget the bounces
int level = gpio_get_level(BUTTON_GPIO);
if (level == stable) {
continue; // a glitch that settled back where it started
}
stable = level;
if (level == 0) {
presses++;
speed = (speed + 1) % (sizeof periods_us / sizeof periods_us[0]);
ESP_ERROR_CHECK(esp_timer_restart(blink_timer, periods_us[speed]));
uint32_t edges = raw_edges;
printf("press %" PRIu32 ": %" PRIu32 " raw edges since last press, blink period %" PRIu64 " ms\n",
presses, edges - seen, periods_us[speed] / 1000);
seen = edges;
}
}
}
void app_main(void)
{
led_strip_config_t strip = {
.strip_gpio_num = RGB_LED_GPIO,
.max_leds = 1,
.led_model = LED_MODEL_WS2812,
.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB,
};
led_strip_rmt_config_t rmt = {.clk_src = RMT_CLK_SRC_DEFAULT, .resolution_hz = 10 * 1000 * 1000};
ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip, &rmt, &led));
gpio_config_t btn = {
.pin_bit_mask = 1ULL << BUTTON_GPIO,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE, // internal weak pull-up; the button pulls to ground
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_ANYEDGE, // press and release
};
ESP_ERROR_CHECK(gpio_config(&btn));
edge_queue = xQueueCreate(8, sizeof(uint32_t));
xTaskCreate(button_task, "button", 3072, NULL, 5, NULL);
ESP_ERROR_CHECK(gpio_install_isr_service(0));
ESP_ERROR_CHECK(gpio_isr_handler_add(BUTTON_GPIO, button_isr, NULL));
const esp_timer_create_args_t args = {.callback = blink_cb, .name = "blink"};
ESP_ERROR_CHECK(esp_timer_create(&args, &blink_timer));
ESP_ERROR_CHECK(esp_timer_start_periodic(blink_timer, periods_us[0]));
printf("Press the Boot button to change the blink period.\n");
}
The interrupt is set on both edges, so the task sees presses and releases. After any edge it waits at least 20 ms, empties the queue of the bounces that arrived meanwhile, and reads the pin. The blink timer never notices any of this.
The Arduino version
// target: esp32c5 sdk: arduino-esp32 tier: 1
// GPIO interrupt, debounce and non-blocking blink with arduino-esp32 3.3.x.
// The Boot button shorts GPIO28 to ground. loop() never calls delay(), so it
// checks the button and the LED thousands of times a second.
const uint8_t BUTTON_PIN = 28; // Boot button, pressed = LOW
const unsigned long DEBOUNCE_MS = 20; // the pin must be quiet this long
const unsigned long PERIODS_MS[] = {1000, 500, 250, 125};
volatile bool edge_seen = false; // set by the ISR, cleared by loop()
volatile uint32_t raw_edges = 0; // bounces included
void ARDUINO_ISR_ATTR on_edge() {
raw_edges++;
edge_seen = true;
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), on_edge, CHANGE);
Serial.println("Press the Boot button to change the blink period.");
}
void loop() {
static int stable = HIGH; // released
static unsigned long last_edge_ms = 0;
static bool pending = false; // an edge happened and is not judged yet
static unsigned long last_blink_ms = 0;
static bool led_on = false;
static size_t speed = 0;
static uint32_t presses = 0, seen = 0;
unsigned long now = millis();
// 1. Button: restart the quiet-time clock on every edge, decide once it expires.
if (edge_seen) {
edge_seen = false;
last_edge_ms = now;
pending = true;
}
if (pending && now - last_edge_ms >= DEBOUNCE_MS) {
pending = false;
int level = digitalRead(BUTTON_PIN);
if (level != stable) {
stable = level;
if (level == LOW) {
presses++;
speed = (speed + 1) % (sizeof PERIODS_MS / sizeof PERIODS_MS[0]);
uint32_t edges = raw_edges;
Serial.printf("press %lu: %lu raw edges since last press, blink period %lu ms\n",
(unsigned long)presses, (unsigned long)(edges - seen), PERIODS_MS[speed]);
seen = edges;
}
}
}
// 2. LED: toggle when its period has passed, without waiting for it.
if (now - last_blink_ms >= PERIODS_MS[speed]) {
last_blink_ms = now;
led_on = !led_on;
rgbLedWrite(RGB_BUILTIN, 0, 0, led_on ? 16 : 0);
}
}
ARDUINO_ISR_ATTR is the core’s marker for interrupt handlers. In arduino-esp32 3.3.13 it expands to IRAM_ATTR, which places the function in internal RAM, only when the core is configured with CONFIG_ARDUINO_ISR_IRAM, and to nothing otherwise. loop() contains no delay(), so the button and the LED are both checked on every pass.
The Raspberry Pi Pico 2 W version
Wire a push button between GP15 and any GND pin. The Pico 2 W’s LED is not on an RP2350 pin at all. It hangs off the CYW43439 wireless chip (its pin WL_GPIO0), so the program links pico_cyw43_arch_none and switches the LED with cyw43_arch_gpio_put() from the main loop, not from the timer callback, which runs in interrupt context. Build with Pico SDK 2.3.1 and -DPICO_BOARD=pico2_w.
// target: pico2_w sdk: pico-sdk-2.3.1 tier: 1
// GPIO interrupt, debounce and a repeating timer on the Raspberry Pi Pico 2 W.
// Wire a push button from GP15 to any GND pin. The internal pull-up holds the
// pin high, so a press reads low. (Pulling up rather than down also sidesteps
// RP2350 erratum E9, which weakens the internal pull-down on A2 silicon.)
#include <stdio.h>
#include "pico/cyw43_arch.h"
#include "pico/stdlib.h"
#define BUTTON_PIN 15
#define DEBOUNCE_US 20000
static volatile bool edge_seen;
static volatile uint32_t last_edge_us; // 32 bits: one store, so no torn reads
static volatile uint32_t raw_edges;
static volatile bool blink_due;
static const uint32_t periods_ms[] = {1000, 500, 250, 125};
// Interrupt context: record the time and leave.
static void on_edge(uint gpio, uint32_t events)
{
(void)gpio;
(void)events;
raw_edges++;
last_edge_us = time_us_32();
edge_seen = true;
}
// Also interrupt context. The LED sits on the CYW43 chip, so the main loop drives it.
static bool on_tick(repeating_timer_t *t)
{
(void)t;
blink_due = true;
return true; // keep repeating
}
int main(void)
{
stdio_init_all();
if (cyw43_arch_init() != 0) {
printf("CYW43 init failed\n");
return 1;
}
gpio_init(BUTTON_PIN);
gpio_set_dir(BUTTON_PIN, GPIO_IN);
gpio_pull_up(BUTTON_PIN);
gpio_set_irq_enabled_with_callback(BUTTON_PIN, GPIO_IRQ_EDGE_FALL | GPIO_IRQ_EDGE_RISE, true, &on_edge);
size_t speed = 0;
repeating_timer_t timer;
add_repeating_timer_ms((int32_t)periods_ms[speed], on_tick, NULL, &timer);
bool stable = true, led = false, pending = false; // true = released
uint32_t presses = 0, seen = 0;
for (;;) {
if (edge_seen) {
edge_seen = false;
pending = true;
}
if (pending && (uint32_t)(time_us_32() - last_edge_us) >= DEBOUNCE_US) {
pending = false;
bool level = gpio_get(BUTTON_PIN);
if (level != stable) {
stable = level;
if (!level) {
presses++;
speed = (speed + 1) % (sizeof periods_ms / sizeof periods_ms[0]);
cancel_repeating_timer(&timer);
add_repeating_timer_ms((int32_t)periods_ms[speed], on_tick, NULL, &timer);
uint32_t edges = raw_edges;
printf("press %lu: %lu raw edges since last press, blink period %lu ms\n",
(unsigned long)presses, (unsigned long)(edges - seen), (unsigned long)periods_ms[speed]);
seen = edges;
}
}
}
if (blink_due) {
blink_due = false;
led = !led;
cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, led);
}
tight_loop_contents();
}
}
The button pulls the pin low against the internal pull-up, for a reason specific to this chip. The RP2350 datasheet lists erratum RP2350-E9 for stepping A2: when a GPIO input sits between the low and high thresholds, the pad leaks about 120 µA and holds itself near 2.2 V, which the internal pull-down is too weak to overcome. The pull-up still works. Raspberry Pi fixed the fault in stepping A3. If you need a pull-down on A2 silicon, the datasheet suggests an external resistor of 8.2 kΩ or less.
For makers
Use the pattern in these examples for every input: pull-up, interrupt or timestamp, quiet-time debounce, and no delay() in the main loop. When a project grows, give each job its own “has its time come?” check, or in ESP-IDF its own task or timer. If a button seems to register double presses, look at the raw edge count the firmware prints before changing anything else.
For product teams
Treat every external input as hostile: debounce it, rate-limit the work it can trigger and make sure an input stuck low cannot keep the device awake and drain the battery. Check the errata for the exact silicon stepping you buy, as RP2350-E9 shows. Avoid strapping pins for inputs that a user or a connected device can hold at reset. Interrupt latency and timer jitter belong in your test plan if anything depends on them.
Exercise
- Flash the ESP-IDF or Arduino version and press the Boot button ten times. Record the raw edge counts the serial monitor prints. What is the largest?
- Set the debounce window to 1 ms and repeat. Count how many presses are now reported twice.
- Add a long-press action: if the button stays down for more than one second, turn the LED red. Use a timestamp or a one-shot timer, not a delay.
- On a Pico 2 W, move the button to GP14 and change the code so it still works.
Summary
delay()andvTaskDelay()stop that loop from doing anything else. Compare timestamps or use timers instead.- A button needs a pull-up (or pull-down) so the pin never floats. The DevKitC-1 Boot button shorts GPIO28 to ground, and the board fits no debounce capacitor.
- An ISR should only record the event. Let a task or the main loop do the work.
- Debounce by waiting for a quiet period after the last edge, then reading once.
- Check errata: on RP2350 stepping A2 the internal pull-down can fail (RP2350-E9), so pull up instead.
Further reading
- Espressif Systems, ESP-IDF Programming Guide v6.1.1 for ESP32-C5, the GPIO and “ESP Timer (High Resolution Timer)” pages.
- Espressif Systems, ESP32-C5-DevKitC-1 Schematic, V1.2, button and LED sheet.
- Raspberry Pi Ltd, RP2350 Datasheet, Appendix D.5.1, “RP2350-E9”.
- Raspberry Pi Ltd, Raspberry Pi Pico 2 W Datasheet, section 3.2 on GPIO and the pinout notes on WL_GPIO0.