ESP32 GPIO Tutorial with ESP-IDF: Blink LED and Read Button
GPIO is the first peripheral that every embedded developer learns, and it is the same with ESP32 as well. It is also the peripheral that causes the most surprises in the beginning. Some pins behave differently while the chip boots, a few pins cannot be used as outputs at all, and a wrong pin choice can make the board look dead even though the code is correct.
In this tutorial, we will configure the GPIO pins of the ESP32 using ESP-IDF and the gpio_config() function. We will connect an LED to one pin and a push button to another, blink the LED, read the state of the button, and finally toggle the LED every time the button is pressed. I will also explain the pins that are safe to use, why the LED needs a resistor, and why a button input needs a pull-up resistor.
I am using the ESP32 DevKit with the WROOM-32 module. At the end of the tutorial, you will see the LED blinking on the breadboard and the button presses appearing in the serial monitor. The project files are available to download at the bottom of the page.
This is the first tutorial in the ESP32 Fundamentals series. If you want to see how the serial output works in more detail, the ESP32 UART tutorial covers it, and the FreeRTOS introduction explains the vTaskDelay() function that we use for the delays.
Table of contents
What is GPIO on the ESP32
GPIO stands for General Purpose Input Output. A GPIO pin is a pin of the chip whose job is decided by the software, so the same pin can drive an LED in one project and read a button in another. The ESP32 chip has 34 GPIO pads, numbered from GPIO0 to GPIO39 with a few numbers missing, and every pad that you use is controlled through the same set of functions in the ESP-IDF driver/gpio.h header.
Not every pad is available on the board, and not every available pad is free to use. Six of the pins, GPIO6 to GPIO11, are connected to the flash memory inside the WROOM-32 module, so they must never be touched. The remaining pins have different capabilities, which we will go through in the next sections.
Input, output and input/output pins
Most ESP32 pins can work in both directions. In the output mode, the pin drives its voltage to either 0 V or 3.3 V, and that is how we switch an LED on and off. In the input mode, the pin only measures the voltage that the outside circuit applies, and the software reads it as a 0 or a 1, which is how we read a button.
ESP-IDF also provides the GPIO_MODE_INPUT_OUTPUT mode, in which the pin drives a level and still allows us to read that level back. Both modes are also available in the open-drain variety, where the pin can only pull the line low and an external resistor pulls it high, but we do not need that for an LED and a button.
Input-only pins (GPIO34 to GPIO39 on WROOM-32)
The pins GPIO34, 35, 36 and 39 can only be used as inputs. GPIO37 and GPIO38 have the same limitation, but most development boards do not expose them. These pins have no output driver inside the chip, so a call to gpio_set_level() on them does nothing useful, and gpio_config() returns an error if you request an output mode.
They also have no internal pull-up or pull-down resistors. If you connect a button to one of these pins, you have to add an external resistor to the circuit, which is the reason I will not use them in this tutorial.
Strapping pins to avoid (GPIO0, 2, 5, 12, 15)
The ESP32 reads the voltage of a few pins at the moment it comes out of reset, and it uses these voltages to decide how to start. These are called the strapping pins, and on the WROOM-32 they are GPIO0, GPIO2, GPIO5, GPIO12 and GPIO15.
GPIO0 is the most important one. If it is held low during reset, the chip enters the download mode and waits for new firmware instead of running your program. This is how the BOOT button on the board works. GPIO2 must be low or floating for the download mode to work, and many boards have the on-board LED connected to it. GPIO12 selects the voltage of the flash memory, and a high level on this pin at reset can stop the module from booting at all. GPIO5 and GPIO15 affect the timing of the SDIO interface, and a low level on GPIO15 also silences the boot messages on the serial port.
These pins work as normal GPIOs after the boot is complete, but a circuit connected to them can interfere with the start-up. The simplest way to avoid trouble is to use other pins for the simple projects.
Maximum current per pin and why you need a resistor
The output of an ESP32 pin is not a power supply. With the default drive strength, a pin is designed for about 20 mA, and the absolute maximum rating in the datasheet is 40 mA. Staying below these numbers is not enough for a long-lasting design, so I keep the current of a single pin to around 10 mA or less.
An LED has almost no resistance once it starts to conduct, which means that the current is limited only by the resistor that we place in series. A red LED drops about 2 V, so with a 3.3 V pin and a 330 Ω resistor, the current is (3.3 − 2.0) / 330, which is close to 4 mA. This is more than enough to make the LED clearly visible, and it keeps the pin well inside its limits. Without the resistor, the LED would try to draw far more current than the pin can supply, and it could damage the LED, the pin, or both.
ESP32 Pull-up and Pull-down Resistors
A push button is a simple switch. When it is pressed, it connects its two terminals, and when it is released, the terminals are disconnected. This creates a problem for the input pin, because the button can only connect the pin to a voltage, and it cannot tell the pin what to read while the button is open.
Floating inputs explained
If nothing is connected to an input pin, the pin is said to be floating. The input of the ESP32 has a very high impedance, so even a small amount of electrical noise from your hand, the breadboard or a nearby wire can move the voltage above or below the switching threshold. The software then reads random zeros and ones, and the values can change from one read to the next without anyone touching the button.
The fix is to give the pin a known default level with a resistor. A pull-up resistor connects the pin to 3.3 V, so the pin reads 1 when nothing else drives it. A pull-down resistor connects the pin to ground, so it reads 0 by default. The resistor is large enough that the button can easily overpower it when the button is pressed.
In this tutorial, I use a pull-up resistor and connect the other side of the button to ground. The pin therefore reads 1 while the button is released and 0 while it is pressed, which is the reverse of what many beginners expect. The diagram below shows how this circuit works.
Internal pull-up/pull-down on the ESP32
Most ESP32 pins have a pull-up and a pull-down resistor built into the chip, which is the reason we do not have to add one to the breadboard. The value is roughly 45 kΩ, and each one can be enabled or disabled separately in the pin configuration. We will enable the pull-up on the button pin, and the button then only needs one wire to the pin and one wire to ground.
The input-only pins GPIO34 to GPIO39 are the exception, because they do not have these internal resistors. A button on one of those pins needs an external pull-up resistor.
Wiring the LED and Button
The LED is connected through the 330 Ω resistor to one GPIO pin, and the other leg of the LED goes to ground. The button is connected between the second GPIO pin and ground. Pay attention to the LED polarity, because it only conducts in one direction. The longer leg is the anode, and it must face the resistor and the GPIO pin. The shorter leg is the cathode, and it goes to ground.
Pin table: WROOM-32
I picked pins that are not strapping pins. The table below shows the wiring between ESP32, button and the LED.
| Connection | ESP32 WROOM-32 |
|---|---|
| LED (through 330 Ω) | GPIO4 |
| Push button | GPIO13 |
| Ground for LED and button | GND |
Creating the ESP-IDF Project
The project is created in Espressif-IDE, and the steps are the same for the other ESP32 boards as well. I will use the hello_world template as a starting point and replace its code afterwards.
- Open Espressif-IDE and go to File → New → Espressif IDF Project.
- Select the option to create the project using one of the templates.
- Choose
hello_worldproject to get started. - Enter a project name, for example
esp32_gpio. - Select your chip from the launch target list, either
esp32oresp32c3, or any other ESP32 board you have. - Click Finish. The IDE generates the project, and the source file
hello_world_main.cis available inside themainfolder. We will write our code in this file.
The template does not link the GPIO driver by default, and without it the build stops with the error driver/gpio.h: No such file or directory. To fix this, the main component has to list the driver in its PRIV_REQUIRES field.
Open main/CMakeLists.txt and add the GPIO driver to the component requirements, as shown below.
idf_component_register(SRCS "hello_world_main.c"
PRIV_REQUIRES spi_flash esp_driver_gpio
INCLUDE_DIRS "")The component esp_driver_gpio is available from ESP-IDF 5.2 onwards. If you use an older version, write driver in place of esp_driver_gpio.
Configuring GPIO with gpio_config()
Every pin in ESP-IDF is set up before use, and the function gpio_config() does this for one or more pins at the same time. It takes a pointer to a structure of the type gpio_config_t, which describes what the pins should do.
The gpio_config_t structure explained
The structure has five fields that matter for this tutorial. The field pin_bit_mask is a 64-bit number in which every bit stands for one GPIO. To select GPIO4, we set bit 4 by writing 1ULL << 4. The suffix ULL makes the number a 64-bit value. This is required because a normal 32-bit integer cannot hold the bits of pins above GPIO31, and the compiler would silently give the wrong result. To configure several pins with the same settings, we combine their masks with the OR operator.
The field mode selects the direction, and the common values are GPIO_MODE_INPUT, GPIO_MODE_OUTPUT and GPIO_MODE_INPUT_OUTPUT. The fields pull_up_en and pull_down_en enable or disable the internal resistors. Here we need to provide GPIO_PULLUP_ENABLE, GPIO_PULLUP_DISABLE or the matching pull-down constants. The last field is intr_type, which selects the interrupt on the pin. We do not use interrupts in this tutorial, so it is set to GPIO_INTR_DISABLE.
Output configuration
The LED pin is an output without any pull resistor, because the LED circuit already defines its level.
gpio_config_t led_conf = {
.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_conf));The function gpio_config() returns an esp_err_t value. I wrap it in ESP_ERROR_CHECK(), which prints a message and restarts the chip when the configuration fails, so an invalid pin is found immediately and not later as a silent problem.
Input configuration
The button pin is an input with the internal pull-up enabled, and the pull-down stays disabled.
gpio_config_t button_conf = {
.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_conf));Both pins need their own structure here, because their modes and pull settings are different. A single call can only apply one set of settings.
ESP32 Blink LED and Read Button Code
All the code goes into hello_world_main.c. The first part contains the includes, the pin definitions and the initialization function, and it stays the same for all three examples below.
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#define LED_GPIO GPIO_NUM_4
#define BUTTON_GPIO GPIO_NUM_13
static const char *TAG = "GPIO_TUTORIAL";
static void gpio_init(void)
{
gpio_config_t led_conf = {
.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_conf));
gpio_config_t button_conf = {
.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_conf));
}The constants such as GPIO_NUM_4 belong to the gpio_num_t type, which is what every GPIO function expects. The variable TAG is the name that appears in front of every log message from this file, and the esp_log.h header provides the ESP_LOGI() macro that prints it.
Blink LED with gpio_set_level()
The function gpio_set_level() takes the pin number and a level. A level of 1 drives the pin to 3.3 V and switches the LED on, and a level of 0 drives it to 0 V and switches it off. In the loop below, the LED stays on for 500 ms and off for 500 ms.
void app_main(void)
{
gpio_init();
while (1)
{
gpio_set_level(LED_GPIO, 1);
ESP_LOGI(TAG, "LED ON");
vTaskDelay(pdMS_TO_TICKS(500));
gpio_set_level(LED_GPIO, 0);
ESP_LOGI(TAG, "LED OFF");
vTaskDelay(pdMS_TO_TICKS(500));
}
}The function vTaskDelay() suspends the task for the given number of RTOS ticks. The macro pdMS_TO_TICKS() converts milliseconds into ticks, so the delay is correct even if the tick rate is changed in the configuration. During the delay, the processor is free to run other tasks, and the idle task can reset the watchdog timer, which is the reason I prefer it to a busy-wait loop. The FreeRTOS task management tutorial explains how tasks and ticks work.
Read button with gpio_get_level()
The function gpio_get_level() returns the current level of the pin, which is 1 for a high voltage and 0 for a low voltage. Because of the pull-up, the value is 1 when the button is released. The code below reads the pin every 20 ms and prints a message only when the level changes, so the terminal does not fill up with repeated lines.
void app_main(void)
{
gpio_init();
int last_level = gpio_get_level(BUTTON_GPIO);
while (1)
{
int level = gpio_get_level(BUTTON_GPIO);
if (level != last_level)
{
ESP_LOGI(TAG, "Button level changed to %d", level);
last_level = level;
}
vTaskDelay(pdMS_TO_TICKS(20));
}
}The variable last_level stores the previous reading, and the if condition compares it with the new one. The 20 ms delay also helps with the contact bounce of the button, which is the short period of rapid on and off changes when the metal contacts touch each other. Most tactile buttons settle in less than 10 ms, so a 20 ms polling interval almost never reads the bounce.
Toggle LED on button press
The final version combines both parts. The LED changes its state once for each press, and it does not change while the button is held down. To do this, we do not look at the level of the button alone, but at the moment when the level changes from 1 to 0, which is the falling edge.
void app_main(void)
{
gpio_init();
int led_state = 0;
int last_level = 1;
while (1)
{
int level = gpio_get_level(BUTTON_GPIO);
if (last_level == 1 && level == 0)
{
led_state = !led_state;
gpio_set_level(LED_GPIO, led_state);
ESP_LOGI(TAG, "Button pressed, LED %s", led_state ? "ON" : "OFF");
}
last_level = level;
vTaskDelay(pdMS_TO_TICKS(20));
}
}The LED state is kept in the variable led_state, and it is flipped with the ! operator on each falling edge. The new value is then written to the pin with gpio_set_level(). If the check were only level == 0, the LED would toggle every 20 ms for as long as the button is held, and it would look like it is flickering.
Testing the ESP32 GPIO Code
Build the project, flash it to the board, and open the serial monitor from the Espressif-IDE toolbar. If the flashing does not start, hold the BOOT button on the board while the IDE shows the connection message, and release it after the upload begins.
LED blinking
With the first example, the LED switches on and off once every second, and the serial monitor prints the LED state in the same rhythm. A line looks like I (1234) GPIO_TUTORIAL: LED ON, where the number in brackets is the uptime (time since boot in milliseconds).
Button press log in the serial monitor
Now load the second example. It only reads the button, so the LED stays off, and the serial monitor shows a line every time the level of the pin changes. When the button is pressed, the log prints Button level changed to 0, and when it is released, the log prints Button level changed to 1. This confirms the pull-up behavior, because the pin reads 1 while the button is released and 0 while it is pressed.
Toggle LED log in the serial monitor
Now load the third example. The LED changes its state at every button press, and each press adds one line to the monitor, so the log shows a repeating pattern of ON and OFF. Pressing and holding the button for a few seconds adds only one line, which confirms that the code reacts to the edge and not to the level.
ESP32 GPIO Troubleshooting
Most of the problems with GPIO come from the wiring, and not from the code, so check the breadboard before changing anything in the program.
LED does not light up
The most common reason is that the LED is connected the wrong way around. Turn it around and test again. Also check that the resistor is in series with the LED and that the LED really connects to the ground pin of the same board. If you use a different pin than the one in this tutorial, make sure that it is not an input-only pin such as GPIO34 to GPIO39, because these cannot drive an output.
Button reads random values
If the serial monitor shows level changes without any button press, the input is floating. Check that pull_up_en is set to GPIO_PULLUP_ENABLE in the button configuration, and that the button pin is not one of GPIO34 to GPIO39, which have no internal pull-up. Also look at the button itself. A 4-pin tactile button has two pairs of legs that are already connected inside, and if the button is turned by 90 degrees on the breadboard, it can connect the pin to ground all the time, and the reading then never changes.
Board does not boot with the button connected
When the board does not start or enters the download mode every time, a strapping pin is usually the cause. A button between GPIO0 and ground puts the chip into the download mode when it is pressed during a reset, and a circuit that pulls GPIO12 high at power-up can prevent the flash from working. Move the button and the LED to pins that are not on the strapping list, such as GPIO4 and GPIO13, and the board will boot normally again.
Conclusion
In this tutorial, we configured the ESP32 GPIO pins using ESP-IDF. We used gpio_config() with the gpio_config_t structure to set one pin as an output for the LED and another as an input with the internal pull-up for the button. We blinked the LED with gpio_set_level(), read the button with gpio_get_level(), and finally toggled the LED on every falling edge of the button input. We also went through the pins that should be avoided, and the reason a floating input needs a pull resistor.
The button in this tutorial is read by polling, which means that the code checks the pin every 20 ms. This works well for simple projects, but it keeps the task busy and can miss very short pulses. In the next tutorial, we will use GPIO interrupts, so that the ESP32 reacts to the button the moment it changes. If you want to control the same LED from a PC instead, the ESP32 UART LED control tutorial shows how to switch it with commands over UART, and the FreeRTOS software timers tutorial shows another way to blink an LED without blocking a task.
Download Project Here
Download the complete Espressif-IDE project here.
If you find this useful, you can support us with a Donation as well.

Arun is an embedded systems engineer with 10+ years of experience in STM32, ESP32, and AVR microcontrollers. He created ControllersTech to share practical tutorials on embedded software, HAL drivers, RTOS, and hardware design — grounded in real industrial automation experience.
Recommended Tools
Essential dev tools
Categories
Browse by platform



