Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Working with GPIO on ESP32 using MicroPython (Step-by-Step)

GPIO = General Purpose Input/Output

These are the digital pins on the ESP32 that you can use to:

  • Control devices like LEDs, buzzers (output)
  • Read devices like buttons, sensors (input)

Step 1: Set up your Environment

Make sure you:

  1. Have MicroPython firmware flashed on your ESP32
  2. Are using Thonny IDE (or any MicroPython editor)
  3. Board is connected and showing up in Thonny

Step 2: Import Required Module

To control GPIO, you need to use the machine module:

from machine import Pin

Step 3: Blink an LED (Output)

Connect an LED to GPIO (e.g., Pin 2 with a resistor)

from machine import Pin
import time

led = Pin(2, Pin.OUT)  # Set GPIO2 as output

while True:
    led.on()       # LED ON
    time.sleep(1)  # Wait 1 second
    led.off()      # LED OFF
    time.sleep(1)

Explanation:

  • Pin(2, Pin.OUT) → Use GPIO 2 as output
  • led.on() → Sets pin HIGH (3.3V)
  • led.off() → Sets pin LOW (0V)

Step 4: Read a Button (Input)

Connect a push button to GPIO14 (with pull-down resistor)

button = Pin(14, Pin.IN)  # Set GPIO14 as input

while True:
    if button.value() == 1:
        print("Button Pressed")
    else:
        print("Button Released")
    time.sleep(0.5)

Explanation:

  • Pin(14, Pin.IN) → GPIO14 is input pin
  • button.value() → Reads pin (0 or 1)

⚠️ If using no external resistor, you can enable internal pull-up:

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

Step 5: Combine Button and LED

LED lights up when button is pressed

led = Pin(2, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_UP)  # active LOW

while True:
    if button.value() == 0:  # Button pressed
        led.on()
    else:
        led.off()
    time.sleep(0.1)

Step 6: Try This Challenge

Task: Blink LED 5 times when the button is pressed.

led = Pin(2, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_UP)

while True:
    if button.value() == 0:
        for i in range(5):
            led.on()
            time.sleep(0.3)
            led.off()
            time.sleep(0.3)

Summary

ModeCode ExamplePurpose
OutputPin(2, Pin.OUT)Control LED, buzzer
InputPin(14, Pin.IN)Read button/sensor
Pull-upPin(14, Pin.IN, Pin.PULL_UP)Input with internal resistor
Read valuepin.value()0 or 1
Set valuepin.on(), pin.off(), pin.value(1)HIGH or LOW

    Leave a Reply

    Your email address will not be published.

    Need Help?