Skip to content

Tutorial

MicroPython ESP32 GPIO: Blink an LED, Read a Button, Debounce and Interrupts

Learn ESP32 GPIO in MicroPython: LED wiring and resistor maths, buttons with pull-ups, non-blocking debounce, interrupts, long presses, safe pins and fixes.

  • 10 min read
  • Updated November 14, 2026
MicroPython ESP32 GPIO: Blink an LED, Read a Button, Debounce and Interrupts

Quick answer: in MicroPython on the ESP32, control pins with machine.Pin. For an LED on GPIO23, use led = Pin(23, Pin.OUT), then led.on(), led.off() or led.value(not led.value()). For a push button wired from GPIO27 to GND, use button = Pin(27, Pin.IN, Pin.PULL_UP); button.value() is 0 when pressed and 1 when released. Debounce presses with a 50 ms check using time.ticks_ms(), or react instantly with button.irq(trigger=Pin.IRQ_FALLING, handler=fn). Keep LEDs behind a 220–330 Ω resistor, and remember ESP32 pins are 3.3 V only.

TaskMicroPython
OutputPin(23, Pin.OUT), .on(), .off(), .value(1)
Input with pull-upPin(27, Pin.IN, Pin.PULL_UP), .value()
Input with pull-downPin(27, Pin.IN, Pin.PULL_DOWN)
Interruptpin.irq(trigger=Pin.IRQ_FALLING, handler=fn)
Onboard LED (most DevKits)Pin(2, Pin.OUT)
Non-blocking timingtime.ticks_ms() and time.ticks_diff()

Which ESP32 pins to use

UseGood choicesAvoid
LED or other output4, 5, 13, 16–19, 21–23, 25–27, 32, 336–11 (flash), 34–39 (input-only)
Button or inputAny of the above, plus 34–39 with an external pull-up0, 2, 12, 15 if the button could be held at power-up
Touch0, 2, 4, 12–15, 27, 32, 33—

GPIO0, 2, 5, 12 and 15 are strapping pins read at boot; something holding them at the wrong level can stop the board starting or uploading. GPIO34–39 are input-only and have no internal pull-up or pull-down. The full picture: ESP32 pinout guide.

1. Blink an LED

Wire GPIO23 → 220 Ω resistor → LED long leg (anode), and the short leg (cathode) → GND.

main.py
from machine import Pin
import time

led = Pin(23, Pin.OUT)

while True:
    led.value(not led.value())     # toggle
    time.sleep(0.5)

No LED handy? Use the onboard LED: Pin(2, Pin.OUT) on most ESP32 DevKit V1 boards (some boards use another pin or have no user LED). On the Raspberry Pi Pico W it's Pin("LED", Pin.OUT).

Resistor maths: R = (3.3 V − LED forward voltage) ÷ current. A red LED (~2.0 V) at 6 mA needs about 220 Ω; 330 Ω gives ~4 mA and is still clearly visible. Blue and white LEDs (~3.0 V) need much less resistance, say 47–100 Ω, and still look dimmer at 3.3 V.

2. Read a push button

Wire one leg of the button to GPIO27 and the other to GND. The internal pull-up holds the pin at 3.3 V (reads 1) until you press, which connects it to GND (reads 0):

main.py
from machine import Pin
import time

button = Pin(27, Pin.IN, Pin.PULL_UP)

while True:
    print("pressed" if button.value() == 0 else "released")
    time.sleep(0.2)
WiringPin modePressedReleased
Button to GND (recommended)Pin.PULL_UP01
Button to 3.3 VPin.PULL_DOWN10
Pin with no pull resistorPin.IN aloneRandomRandom ("floating")

The internal pull resistors are weak (around 45 kΩ). For long wires or noisy environments, add an external 10 kΩ pull-up to 3.3 V.

3. Toggle the LED with clean, debounced presses

Mechanical contacts bounce for a few milliseconds, so one press can look like several. This loop counts a press only after the button has been stable for 50 ms:

main.py
from machine import Pin
import time
led = Pin(23, Pin.OUT)
button = Pin(27, Pin.IN, Pin.PULL_UP)
DEBOUNCE_MS = 50
stable = button.value()
last_change = time.ticks_ms()
last_raw = stable
while True:
    raw = button.value()
    if raw != last_raw:
        # something changed
        last_change = time.ticks_ms()
        last_raw = raw
        if time.ticks_diff(time.ticks_ms(), last_change) > DEBOUNCE_MS and raw != stable:
            stable = raw
            if stable == 0:
                # a clean press
                led.value(not led.value())
                print("LED", "ON" if led.value() else "OFF")
                time.sleep_ms(5)
                # other work could go here

Use time.ticks_diff() rather than subtracting ticks_ms() values directly: the counter wraps around, and ticks_diff handles that correctly.

4. React instantly with an interrupt

An interrupt (IRQ) runs a function the moment the pin changes, even while the main loop is busy:

main.py
from machine import Pin
import time
led = Pin(23, Pin.OUT)
button = Pin(27, Pin.IN, Pin.PULL_UP)
pressed = False
last_irq = 0
def on_press(pin):
    global pressed, last_irq
    now = time.ticks_ms()
    if time.ticks_diff(now, last_irq) > 200:
        # ignore bounce
        pressed = True
        last_irq = now
        button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
        while True:
            if pressed:
                pressed = False
                led.value(not led.value())
                print("Toggled")
                time.sleep_ms(10)
                # main loop can do slow work here

Keep interrupt handlers tiny: set a flag and return. Don't print, allocate big objects or call slow functions inside them; do that in the main loop. Pin.IRQ_RISING fires on release, and Pin.IRQ_FALLING | Pin.IRQ_RISING on both.

5. Short press vs long press

main.py
from machine import Pin
import time

button = Pin(27, Pin.IN, Pin.PULL_UP)

def wait_for_press():
    while button.value() == 1:
        time.sleep_ms(10)
    start = time.ticks_ms()
    while button.value() == 0:
        time.sleep_ms(10)
    return time.ticks_diff(time.ticks_ms(), start)

while True:
    held = wait_for_press()
    if held > 1000:
        print("Long press ({} ms)".format(held))
    elif held > 40:
        print("Short press")

One button, two actions: a short press toggles a light, a long press enters setup mode.

Several LEDs and buttons

Lists keep code short when you add more hardware. This pairs three buttons with three LEDs, each button toggling its own LED:

main.py
from machine import Pin
import time
leds
= [Pin(n, Pin.OUT, value=0) for n in (23, 22, 21)]
buttons = [Pin(n, Pin.IN, Pin.PULL_UP) for n in (27, 26, 25)]
last
= [1, 1, 1]
# previous reading of each button
while True:
    for i, b in enumerate(buttons):
        v = b.value()
        if v == 0 and last[i] == 1:
            # falling edge = new press
            leds[i].value(not leds[i].value())
            time.sleep_ms(30)
            # simple debounce
            last[i] = v
            time.sleep_ms(5)

A running light (one LED at a time moving along the row) is the classic next exercise:

main.py
while True:
    for led in leds:
        led.on(); time.sleep_ms(150); led.off()

Each LED needs its own resistor; don't share one resistor between several LEDs, or brightness changes as more turn on.

6. Organise a real project

As soon as you have more than one input or output, split the code into small functions and run it from main.py (which starts automatically at boot; see boot.py and main.py explained):

main.py
# main.py
from machine import Pin
import time

LED_PIN, BUTTON_PIN = 23, 27
led = Pin(LED_PIN, Pin.OUT, value=0)          # start OFF
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)

def setup():
    print("Ready: press the button to toggle the LED")

def loop():
    # read inputs, update outputs, never block for long
    pass

setup()
while True:
    loop()
    time.sleep_ms(10)

Named constants for pins make it easy to move a wire later. Starting outputs in a known state (value=0) matters as soon as you drive relays instead of LEDs.

7. Troubleshooting

SymptomLikely causeFix
LED never lightsLED reversed, missing resistor connection, wrong pinLong leg to the GPIO side; check the pin number on the silkscreen
LED very dimResistor too large, or a blue/white LED at 3.3 VSmaller resistor (100–150 Ω for blue/white)
Button reads random 0/1Floating inputPin.PULL_UP (or an external 10 kΩ)
Button "works backwards"Pull-up wiring: pressed = 0Invert your check
One press toggles twiceContact bounce50 ms debounce or a time check in the IRQ
Pull-up does nothing on GPIO34–39No internal pulls on those pinsExternal 10 kΩ to 3.3 V
Board won't boot with the button heldButton on a strapping pin (0, 2, 12, 15)Move it to GPIO27 or similar
ValueError: invalid pinPin doesn't exist or is reserved (6–11)Choose a valid GPIO
Interrupt causes MemoryError or crashesPrinting or allocating inside the handlerSet a flag only; work in the main loop

FAQ

What's the difference between value(), on() and off()? on() and off() set the output; value(x) sets it and value() with no argument reads it.

Can I read an output pin's state? Usually yes on the ESP32 in MicroPython, but it's clearer to keep the state in a variable, especially if you later port to another board.

How much current can a pin supply? Keep it to about 20 mA per pin. Relays, motors and buzzers need a transistor or a driver module.

Does the same code work on the Raspberry Pi Pico? Yes, apart from pin numbers: any GPn number works, and the Pico W's LED is Pin("LED").

Next steps

Official reference: MicroPython machine.Pin.

Electrical checks before connecting GPIO

A GPIO is a logic input or output, not a general-purpose power supply. On common ESP32 boards, the pins use 3.3 V logic and are not 5 V tolerant. Never connect a 5 V signal directly to an ESP32 input. Use a suitable level shifter or a correctly calculated divider for a signal that must be reduced, and check the input circuit's impedance and speed requirements before choosing a divider.

Before powering a new circuit, check the board pinout for strapping pins, input-only pins, flash-connected pins and pins used by onboard peripherals. A pin that works in a simple blink sketch may affect boot mode if an external circuit forces it to the wrong level during reset. For a first experiment, choose a known general-purpose pin from the exact board's pinout and avoid assuming that every ESP32 variant exposes the same GPIO set.

For a button wired from GPIO to ground with an internal pull-up, the input reads HIGH when released and LOW when pressed. That is active-low logic. Write the program and wiring notes with this polarity stated explicitly; otherwise, a later change to an external pull-down resistor can invert the behavior unexpectedly.

Measure timing and handle switch bounce

Mechanical buttons do not produce one perfectly clean transition. Their contacts can open and close several times over a few milliseconds. A debounce interval prevents those transitions from being interpreted as multiple presses. Choose an interval appropriate to the switch and application, and use a non-blocking time check when the program also needs to read sensors or maintain a network connection.

Interrupt handlers should do as little as possible. Set a flag or increment a counter, then process the event in the main program. Avoid printing, allocating complex objects, sleeping or performing network operations inside an interrupt handler. If the main loop reads a counter that an interrupt can update, use the platform's recommended atomic or critical-section approach to avoid inconsistent values.

Finally, test reset behavior as well as normal operation: power-cycle the board, press the button during boot, and confirm that the chosen GPIO does not accidentally select a download or boot mode. This catches wiring problems that a successful run after USB reset can hide.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.