LOGBOOK

HELP

Quiz Entry - updated: 2026.10.20

Write the core of an ESP-IDF button-to-LED program, with the LED on GPIO5 and an active-low button on GPIO4. Which GPIO calls does it need?

Configure GPIO5 as output and GPIO4 as input with the pull-up, then loop: read the button with gpio_get_level, set the LED with gpio_set_level, sleep 10 ms with vTaskDelay.

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"

#define LED_GPIO    GPIO_NUM_5
#define BUTTON_GPIO GPIO_NUM_4

void app_main(void)
{
    gpio_reset_pin(LED_GPIO);
    gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);

    gpio_reset_pin(BUTTON_GPIO);
    gpio_set_direction(BUTTON_GPIO, GPIO_MODE_INPUT);
    gpio_set_pull_mode(BUTTON_GPIO, GPIO_PULLUP_ONLY);

    while (1) {
        int pressed = (gpio_get_level(BUTTON_GPIO) == 0);  /* active low */
        gpio_set_level(LED_GPIO, pressed);
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}

What each call does:

Call Purpose
gpio_reset_pin Puts the pin back into a plain GPIO state (it may have been assigned to another peripheral)
gpio_set_direction Makes the pin an output (LED) or an input (button)
gpio_set_pull_mode(..., GPIO_PULLUP_ONLY) Enables the internal pull-up, so the open button reads 1
gpio_get_level Returns 0 or 1. With the button to GND, 0 means pressed
gpio_set_level Drives the LED pin to 3.3 V (1, on) or 0 V (0, off)
vTaskDelay(pdMS_TO_TICKS(10)) Blocks the task for 10 ms. This lets other tasks run and filters most bounce

Here the LED follows the button: on while held. app_main itself runs as a FreeRTOS task, so the loop can live there. In a larger program it would be its own task created with xTaskCreate. The same settings can also be made in one call with gpio_config() and a gpio_config_t struct, which is what Espressif's examples use.

Go deeper:

From Quiz: SIOT / GPIO Input and I2C Sensor Wiring on the ESP32 | Updated: Oct 20, 2026