GPIO Programming in ESP32
GPIO stands for General-Purpose Input/Output. GPIO pins allow an ESP32 microcontroller to interact with external electronic components such as LEDs, push buttons, sensors, buzzers, relays, and motor drivers.
GPIO programming is one of the most important skills in IoT development because many projects depend on reading inputs from the physical world and controlling outputs in response.
In this lesson, you will learn GPIO fundamentals, pin modes, digital input and output, pull-up and pull-down resistors, analog input, PWM, interrupts, debouncing, and practical ESP32 projects.
1. What Is GPIO?
GPIO pins are configurable connections between a microcontroller and external hardware.
A GPIO pin can commonly be configured as an input or an output, depending on the capabilities of the specific pin.
GPIO as an Input
An input pin reads a signal from an external component.
Examples:
- Push button
- Motion sensor
- IR obstacle sensor
- Digital temperature sensor
- Limit switch
GPIO as an Output
An output pin sends a logic signal to control an external circuit.
Examples:
- LED
- Buzzer control input
- Relay module input
- Motor driver input
- Digital control signal
Example
pinMode(2, OUTPUT); digitalWrite(2, HIGH);
This configures GPIO 2 as an output and sets it HIGH.
The exact voltage and electrical behavior depend on the ESP32 chip and its GPIO configuration. ESP32 GPIO normally uses 3.3 V logic.
2. Understanding ESP32 GPIO Pins
Different ESP32 development boards expose different sets of GPIO pins. Even chips in the ESP32 family do not all have identical GPIO capabilities.
On the original ESP32, commonly used pins include GPIO 4, 5, 18, 19, 21, 22, 23, 25, 26, 27, 32, and 33, subject to board design and peripheral configuration.
Important Pin Considerations
| GPIO group | Important consideration |
|---|---|
| GPIO 0, 2, 5, 12, 15 on classic ESP32 | Some are strapping pins and can affect boot behavior |
| GPIO 6–11 on many classic ESP32 modules | Commonly connected to SPI flash and generally unavailable for ordinary use |
| GPIO 34–39 on classic ESP32 | Input-only; no normal digital output |
| GPIO 21 and 22 on many classic ESP32 boards | Commonly used for I2C, but pin assignments can be changed |
| GPIO 18 and 19 on many classic ESP32 boards | Commonly used for SPI, depending on configuration |
| GPIOs connected to onboard hardware | May be unavailable or shared with onboard components |
Always check the pinout for your exact development board before connecting components.
3. GPIO Programming Functions
The Arduino-ESP32 framework provides several functions for controlling GPIO pins.
| Function | Purpose |
|---|---|
pinMode() | Configures a pin's operating mode |
digitalWrite() | Sets a digital output HIGH or LOW |
digitalRead() | Reads a digital input |
analogRead() | Reads an analog input through the ADC |
attachInterrupt() | Registers an interrupt callback |
detachInterrupt() | Removes an interrupt callback |
millis() | Returns elapsed milliseconds since startup |
digitalPinToInterrupt() | Converts a pin number to an interrupt identifier where applicable |
The availability and behavior of individual features depend on the target chip and Arduino-ESP32 version.
4. Configuring a GPIO with pinMode()
The pinMode() function configures the operating mode of a pin.
Syntax
pinMode(pin, mode);
Common modes include:
INPUT: Reads an external logic signal.OUTPUT: Drives a digital output.INPUT_PULLUP: Enables an internal pull-up resistor where supported.INPUT_PULLDOWN: Enables an internal pull-down resistor where supported.
Example
#include <Arduino.h> const int LED_PIN = 2; const int BUTTON_PIN = 4; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { }
In this example, GPIO 2 is configured as an output, while GPIO 4 is configured as an input with a pull-up resistor.
5. Digital Output with digitalWrite()
The digitalWrite() function sets a digital output to HIGH or LOW.
Syntax
digitalWrite(pin, value);
HIGH: Sets the output to its high logic state.LOW: Sets the output to its low logic state.
Example: Turning an LED On and Off
#include <Arduino.h> const int LED_PIN = 2; void setup() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { digitalWrite(LED_PIN, HIGH); delay(1000); digitalWrite(LED_PIN, LOW); delay(1000); }
How It Works
- The LED pin is configured as an output.
- The program sets the output HIGH.
- The LED stays in that state for approximately one second.
- The program sets the output LOW.
- The process repeats.
This example assumes the LED circuit is wired to turn on when the GPIO is HIGH. Some onboard LEDs or modules are active-low and behave in the opposite way.
Electrical safety: Do not connect an LED directly without an appropriate current-limiting resistor. Never use a GPIO pin to power a motor or other high-current load directly.
6. Digital Input with digitalRead()
The digitalRead() function reads the current digital logic state of a GPIO input.
Syntax
int state = digitalRead(pin);
The returned value is normally HIGH or LOW.
Example: Reading a Push Button
#include <Arduino.h> const int BUTTON_PIN = 4; void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { int buttonState = digitalRead(BUTTON_PIN); if (buttonState == LOW) { Serial.println("Button pressed"); } else { Serial.println("Button released"); } delay(500); }
Button Wiring
With INPUT_PULLUP, connect the button between GPIO 4 and GND.
- Button released: the input is normally HIGH.
- Button pressed: the input becomes LOW.
This is called active-low logic because the pressed state is represented by LOW.
7. Pull-Up and Pull-Down Resistors
A digital input should not be left floating when the circuit requires a stable logic level.
A floating input can pick up electrical noise and produce unpredictable readings.
Pull-Up Resistor
A pull-up resistor holds an input HIGH when nothing is actively pulling it LOW.
pinMode(BUTTON_PIN, INPUT_PULLUP);
When a button connects the pin to GND, the input becomes LOW.
Pull-Down Resistor
A pull-down resistor holds an input LOW when nothing is actively driving it HIGH.
pinMode(BUTTON_PIN, INPUT_PULLDOWN);
The exact internal pull resistor availability depends on the GPIO and chip.
When Should You Use Each?
| Configuration | Typical wiring | Idle state |
|---|---|---|
INPUT_PULLUP | Button between GPIO and GND | HIGH |
INPUT_PULLDOWN | Button between GPIO and 3.3 V | LOW |
INPUT | External circuit supplies a defined signal | Depends on circuit |
Do not apply 5 V directly to an ESP32 GPIO. Use a suitable level shifter or input circuit if an external device produces a voltage above the permitted GPIO input range.
8. Practical Project: Button-Controlled LED
This project turns an LED on while a button is pressed.
Hardware Required
- ESP32 development board
- One LED
- One suitable current-limiting resistor
- One push button
- Jumper wires
- Breadboard
Connections
| Component | ESP32 connection |
|---|---|
| LED anode through resistor | GPIO 2 |
| LED cathode | GND |
| Button terminal 1 | GPIO 4 |
| Button terminal 2 | GND |
Check your board's pinout before using GPIO 2.
Code
#include <Arduino.h> const int LED_PIN = 2; const int BUTTON_PIN = 4; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { bool buttonPressed = digitalRead(BUTTON_PIN) == LOW; digitalWrite(LED_PIN, buttonPressed ? HIGH : LOW); if (buttonPressed) { Serial.println("LED ON"); } delay(50); }
This simple version does not implement debouncing, so a mechanical button may produce unstable readings around the instant it is pressed or released.
9. Analog Input with analogRead()
Some sensors produce a continuously varying voltage instead of a simple HIGH or LOW signal.
Examples include:
- Potentiometers
- Analog light sensors
- Certain gas sensor modules
- Analog temperature sensors
- Analog joystick outputs
The ESP32 uses an Analog-to-Digital Converter (ADC) to convert a supported input voltage into a digital value.
Syntax
int sensorValue = analogRead(pin);
Example: Reading a Potentiometer
#include <Arduino.h> const int SENSOR_PIN = 34; void setup() { Serial.begin(115200); } void loop() { int sensorValue = analogRead(SENSOR_PIN); Serial.print("ADC value: "); Serial.println(sensorValue); delay(500); }
On a classic ESP32 with the common default 12-bit ADC resolution, readings are typically in the range 0–4095.
The actual voltage range, ADC behavior, and supported pins vary by chip and configuration. ADC readings are not automatically calibrated voltage or physical measurements.
Important ADC Notes
- Use an ADC-capable pin.
- Stay within the chip's permitted input voltage range.
- Configure attenuation if necessary.
- Account for sensor calibration and noise.
- Check whether your selected ADC unit is affected by other peripherals on your particular chip.
GPIO 34 is input-only on the classic ESP32 and can be used for analog input on that chip. Do not assume every ESP32-family board has the same pin mapping.
10. PWM Output with LEDC
Pulse-width modulation (PWM) produces a digital signal that switches between HIGH and LOW at a configured frequency. By changing the duty cycle, you can control the average power delivered to a compatible load.
PWM is useful for:
- LED brightness control.
- Compatible motor driver control inputs.
- Generating certain control signals.
On Arduino-ESP32 3.x, common LEDC APIs include ledcAttach() and ledcWrite().
Example: Adjusting LED Brightness
#include <Arduino.h> const int LED_PIN = 2; const int PWM_FREQUENCY = 5000; const int PWM_RESOLUTION = 8; void setup() { Serial.begin(115200); if (!ledcAttach(LED_PIN, PWM_FREQUENCY, PWM_RESOLUTION)) { Serial.println("PWM setup failed"); } } void loop() { for (int duty = 0; duty <= 255; duty++) { ledcWrite(LED_PIN, duty); delay(10); } for (int duty = 255; duty >= 0; duty--) { ledcWrite(LED_PIN, duty); delay(10); } }
Understanding Duty Cycle
With an 8-bit resolution, the duty value ranges from 0 to 255.
0: 0% duty.128: approximately 50% duty.255: maximum duty for this resolution.
The example uses the Arduino-ESP32 3.x LEDC API. Arduino-ESP32 2.x commonly uses ledcSetup() and ledcAttachPin(), so adjust the code to your installed core version.
PWM does not mean that an ESP32 GPIO can safely supply high current. Use a suitable driver circuit for motors and other power-hungry devices.
11. Non-Blocking GPIO Control with millis()
Using delay() is convenient, but long delays stop your application from performing other work in the same loop while the delay is active.
For projects involving sensors, networking, and multiple outputs, use millis() to schedule GPIO changes without long blocking waits.
Example: Non-Blocking LED Blink
#include <Arduino.h> const int LED_PIN = 2; const unsigned long INTERVAL_MS = 1000; unsigned long previousMillis = 0; bool ledState = false; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= INTERVAL_MS) { previousMillis = currentMillis; ledState = !ledState; digitalWrite(LED_PIN, ledState ? HIGH : LOW); } // Other tasks can run here. }
The subtraction-based time comparison handles normal unsigned millis() rollover when used correctly.
This approach allows you to read sensors, check buttons, or process other application logic during the intervals between LED changes.
12. GPIO Interrupts
Interrupts allow a supported hardware event to trigger a callback without requiring the main loop to continuously poll the pin.
They are useful for certain event-driven tasks, such as counting pulses from a sensor.
Basic Syntax
attachInterrupt( digitalPinToInterrupt(pin), callback, mode );
Common modes include:
RISING: Trigger on a LOW-to-HIGH transition.FALLING: Trigger on a HIGH-to-LOW transition.CHANGE: Trigger on either transition.
Availability and behavior depend on the target chip and pin.
Example: Counting Button Events
#include <Arduino.h> const int BUTTON_PIN = 4; volatile unsigned long buttonEvents = 0; void IRAM_ATTR buttonISR() { buttonEvents++; } void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); attachInterrupt( digitalPinToInterrupt(BUTTON_PIN), buttonISR, FALLING ); } void loop() { unsigned long eventCount; noInterrupts(); eventCount = buttonEvents; interrupts(); static unsigned long previousCount = 0; if (eventCount != previousCount) { Serial.print("Button events: "); Serial.println(eventCount); previousCount = eventCount; } delay(20); }
Interrupt Safety
Interrupt service routines should be short and predictable.
- Do not print to Serial from the interrupt handler.
- Avoid delays and blocking functions inside an ISR.
- Use appropriate synchronization for shared data.
volatilealone does not make every shared operation atomic.- Mechanical buttons need debouncing.
- Follow the interrupt requirements of the specific ESP32 target.
The IRAM_ATTR macro is commonly used for ESP32 interrupt handlers, but exact restrictions depend on the target and framework configuration.
13. Button Debouncing
Mechanical switches can generate several rapid electrical transitions when pressed or released. This is called switch bounce.
Without debouncing, one physical press may be counted as several events.
A simple software approach is to accept a state change only after the input has remained stable for a specified period.
Example: Debounced Button
#include <Arduino.h> const int BUTTON_PIN = 4; const unsigned long DEBOUNCE_MS = 40; int lastRawState = HIGH; int stableState = HIGH; unsigned long lastChangeTime = 0; void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { int rawState = digitalRead(BUTTON_PIN); unsigned long currentMillis = millis(); if (rawState != lastRawState) { lastRawState = rawState; lastChangeTime = currentMillis; } if (currentMillis - lastChangeTime >= DEBOUNCE_MS && rawState != stableState) { stableState = rawState; if (stableState == LOW) { Serial.println("Button pressed"); } else { Serial.println("Button released"); } } }
The debounce interval is an example. Select an interval suitable for your switch and application.
This code uses polling and does not require an interrupt.
14. Controlling a Relay with GPIO
Relays allow a low-voltage control system to switch a separate electrical circuit. However, the ESP32 should generally control a compatible relay module rather than directly drive a relay coil.
Example
#include <Arduino.h> const int RELAY_PIN = 25; void setup() { Serial.begin(115200); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, LOW); } void loop() { digitalWrite(RELAY_PIN, HIGH); Serial.println("Relay control HIGH"); delay(2000); digitalWrite(RELAY_PIN, LOW); Serial.println("Relay control LOW"); delay(2000); }
This example assumes the relay module is active-high. Some relay modules are active-low, so the logic may need to be reversed.
Before connecting a relay module, verify:
- Its input voltage requirements.
- Whether it accepts 3.3 V logic.
- Whether it is active-high or active-low.
- Whether it needs a separate power supply.
- Whether the electrical load requires additional protection.
Mains electricity can cause severe injury or death. Do not work on exposed mains wiring unless you are properly qualified and following appropriate electrical safety practices.
15. Reading Multiple GPIO Inputs
Many IoT projects use multiple digital sensors.
You can store pin assignments in arrays and process them with loops.
Example
#include <Arduino.h> const int SENSOR_PINS[] = {4, 16, 17}; const int SENSOR_COUNT = sizeof(SENSOR_PINS) / sizeof(SENSOR_PINS[0]); void setup() { Serial.begin(115200); for (int i = 0; i < SENSOR_COUNT; i++) { pinMode(SENSOR_PINS[i], INPUT_PULLUP); } } void loop() { for (int i = 0; i < SENSOR_COUNT; i++) { int state = digitalRead(SENSOR_PINS[i]); Serial.print("Sensor "); Serial.print(i); Serial.print(": "); Serial.println(state == LOW ? "ACTIVE" : "INACTIVE"); } delay(500); }
This example assumes each sensor or switch safely pulls its input LOW when active and is compatible with the internal pull-up.
Do not assume all digital sensor modules use active-low logic. Check their documentation and wiring.
16. GPIO Output State and Toggle Logic
A common requirement is to toggle an output whenever a button is pressed.
A toggle changes the state from OFF to ON or from ON to OFF.
The basic logic is:
ledState = !ledState;
Here, the logical NOT operator (!) reverses a Boolean value.
For example:
bool ledState = false; ledState = !ledState; // true ledState = !ledState; // false
To build a reliable button-toggle project, combine this state variable with edge detection or debouncing so that one press produces one toggle.
17. GPIO Pin Safety and Electrical Limits
GPIO programming is not only about software. Electrical compatibility is equally important.
Follow these precautions:
- ESP32 GPIO generally operates at 3.3 V logic.
- Never assume a GPIO is 5 V tolerant.
- Do not exceed the permitted input voltage.
- Do not draw excessive current from a GPIO.
- Use a current-limiting resistor for a bare LED.
- Use transistor or MOSFET driver circuits for loads requiring more current.
- Use suitable driver modules for motors and relays.
- Connect grounds appropriately when the circuit design requires a shared reference.
- Check boot-strapping pins before connecting external circuits.
- Avoid pins reserved for flash, PSRAM, or onboard hardware.
- Use level shifting when interfacing with incompatible logic levels.
- Check the exact board schematic and chip datasheet for pin limitations.
18. Common GPIO Errors and Troubleshooting
LED Does Not Turn On
Check:
- GPIO number and board pinout.
- LED polarity and current-limiting resistor.
- Output configuration using
pinMode(). - Whether the circuit is active-high or active-low.
- Whether the chosen pin is reserved or unavailable.
Button Always Reads HIGH
Check:
- Whether the button is connected between the GPIO and GND.
- Whether
INPUT_PULLUPis configured. - Whether the wiring has a reliable ground connection.
- Whether the switch is faulty.
Button Always Reads LOW
Check:
- Whether the pin is permanently connected to GND.
- Whether the wiring is incorrect.
- Whether an external circuit is pulling the pin LOW.
- Whether the sensor uses active-low logic.
Analog Reading Is Always Zero
Check:
- Whether the pin supports ADC.
- Whether the sensor has power.
- Whether the signal and ground connections are correct.
- Whether the input voltage is within the allowed range.
- Whether the selected pin is affected by other hardware configuration.
PWM API Does Not Compile
Check the installed Arduino-ESP32 version. The LEDC API changed between major core versions.
Unexpected Boot Behavior
Check whether an external circuit is forcing a strapping pin to an inappropriate logic level during reset.
19. Best Practices for GPIO Programming
- Define GPIO assignments using named constants.
- Keep hardware-specific pin mapping in a configuration section.
- Use non-blocking timing for responsive applications.
- Use debouncing for mechanical switches.
- Use interrupts only when they provide a real benefit.
- Keep interrupt callbacks short.
- Validate input signals before triggering important actions.
- Use suitable drivers for high-current loads.
- Document active-high and active-low behavior.
- Check pin limitations before connecting hardware.
- Test each circuit independently before integrating it into a larger project.
- Use a multimeter when diagnosing unexpected voltages or wiring issues.
20. Practice Exercises
Beginner
- Blink an LED connected to a safe GPIO pin.
- Read a push button using
INPUT_PULLUP. - Turn an LED on while the button is pressed.
- Read a potentiometer using
analogRead(). - Print sensor values to Serial Monitor at 115200 baud.
Intermediate
- Create a button-toggle circuit with debouncing.
- Fade an LED using PWM.
- Control two LEDs independently.
- Read three digital sensors using an array.
- Build a non-blocking LED blink program using
millis().
Advanced
- Count pulses from a supported sensor using a hardware interrupt.
- Build a relay controller with configurable active-high or active-low logic.
- Combine an analog sensor with a threshold-triggered buzzer.
- Create a multi-sensor alert system without long blocking delays.
- Compare polling and interrupt-based input handling for a pulse-counting application.
Summary
GPIO programming is the foundation of many ESP32 IoT projects.
In this lesson, you learned:
- What GPIO is and how ESP32 pins work.
- How to configure pins with
pinMode(). - How to control digital outputs with
digitalWrite(). - How to read digital inputs with
digitalRead(). - How pull-up and pull-down resistors work.
- How to read analog sensors using
analogRead(). - How to control brightness with PWM.
- How to use
millis()for non-blocking timing. - How interrupts and debouncing work.
- How to control relay modules and multiple inputs.
- How to troubleshoot GPIO problems safely.
Key takeaway: Reliable GPIO programming combines correct code, suitable pin selection, sound circuit design, and an understanding of the electrical limits of your specific ESP32 board.