Skip to content

MicroPython Programming on ESP32

MicroPython Programming on ESP32

This section introduces MicroPython as an alternative programming language for the ESP32. By the end of this section, you will be able to:

  • Flash MicroPython firmware onto an ESP32
  • Write and run Python scripts on ESP32
  • Use the REPL (Read-Eval-Print Loop) for interactive development
  • Read sensor data and control GPIO using Python
  • Understand when to choose MicroPython over Arduino C++
  • Basic Python programming knowledge
  • An ESP32 development board
  • USB-UART driver installed

MicroPython is a lean implementation of Python 3 designed for microcontrollers. It includes a subset of the Python standard library, plus hardware-specific modules for GPIO, I2C, SPI, Wi-Fi, and more.

Key Characteristics:

  • Interactive: REPL (Read-Eval-Print Loop) allows live experimentation
  • Python Syntax: Familiar to anyone who knows Python
  • Filesystem: ESP32 flash is partitioned to include a small filesystem for Python scripts
  • RAM Footprint: Runs in as little as 256 KB RAM
  • Performance: 5-10x slower than compiled C++, but sufficient for most IoT tasks
AspectMicroPythonArduino C++
Development SpeedFast (no compile step)Slower (compile + upload)
Execution SpeedSlower (interpreted)Fast (compiled native)
RAM UsageHigher (interpreter overhead)Lower
Learning CurveLow (if Python known)Moderate (C++ syntax)
Library EcosystemGrowing, but smallerVery large, mature
DebuggingREPL + print statementsSerial print, GDB with JTAG
Real-Time ControlLimited (no preemption)Full (FreeRTOS)
File SizeLarger binary (includes interpreter)Smaller binary
Best ForPrototyping, education, data loggingProduction, precision timing, complex projects

Step 1: Install MicroPython Firmware on ESP32

Section titled “Step 1: Install MicroPython Firmware on ESP32”

Option A: Using esptool (Command Line)

  1. Download the latest MicroPython firmware for ESP32 from micropython.org/download/ESP32_GENERIC/

  2. Install esptool:

    Terminal window
    pip install esptool
  3. Erase the ESP32 flash:

    Terminal window
    esptool.py --chip esp32 --port /dev/cu.usbserial-XXXX erase_flash

    (Replace /dev/cu.usbserial-XXXX with your port)

  4. Flash MicroPython firmware:

    Terminal window
    esptool.py --chip esp32 --port /dev/cu.usbserial-XXXX --baud 460800 write_flash -z 0x1000 ESP32_GENERIC-20231005-v1.21.0.bin

Option B: Using Thonny IDE (GUI — Recommended for Beginners)

  1. Download and install Thonny IDE from thonny.org
  2. Connect the ESP32 via USB
  3. In Thonny, go to Run > Select Interpreter
  4. Choose MicroPython (ESP32)
  5. Select the correct port
  6. Go to Tools > Options > Interpreter
  7. Click Install or update MicroPython
  8. Select the ESP32 variant and click Install
  9. Wait for the installation to complete

Once MicroPython is installed:

  1. Open a serial connection to the ESP32:

    • Using Thonny: The Shell pane automatically connects
    • Using screen (macOS/Linux): screen /dev/cu.usbserial-XXXX 115200
    • Using putty (Windows): Serial connection at 115200 baud
  2. You should see the MicroPython banner:

    MicroPython v1.21.0 on 2023-10-05; ESP32 module with ESP32
    Type "help()" for more information.
    >>>
  3. Test the REPL:

    >>> print("Hello from ESP32!")
    Hello from ESP32!
    >>> import machine
    >>> machine.freq()
    240000000

Create a file named main.py in Thonny (File > New) and save it to the ESP32 (File > Save As > MicroPython Device):

import machine
import time
led = machine.Pin(2, machine.Pin.OUT)
while True:
led.on()
time.sleep(1)
led.off()
time.sleep(1)

After saving as main.py to the ESP32, press the reset button. The script will auto-start because MicroPython executes main.py on boot.

import machine
import dht
import time
# DHT22 connected to GPIO 4
sensor = dht.DHT22(machine.Pin(4))
while True:
try:
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
print(f"Temperature: {temp:.1f} C, Humidity: {humidity:.1f}%")
except Exception as e:
print("Sensor error:", e)
time.sleep(5)
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
ssid = "YourWiFiSSID"
password = "YourWiFiPassword"
print("Connecting to Wi-Fi...")
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(0.5)
print(".", end="")
print()
print("Connected!")
print("IP address:", wlan.ifconfig()[0])

Install the umqtt.simple library (available in the MicroPython package repository):

import network
import time
from umqtt.simple import MQTTClient
import machine
# Wi-Fi connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("YourWiFiSSID", "YourWiFiPassword")
while not wlan.isconnected():
time.sleep(0.5)
# MQTT setup
client = MQTTClient("esp32-client", "192.168.1.100", port=1883)
client.connect()
# Publish a message
client.publish(b"esp32/test", b"Hello from MicroPython!")
print("Message published")
client.disconnect()
  • MicroPython REPL responds to Python commands
  • main.py auto-starts on ESP32 reset
  • LED blinks as programmed
  • Sensor readings are accurate and correctly formatted
  • Wi-Fi connection succeeds with correct IP
  • MQTT message is received by the broker

ESP32 not responding after flashing MicroPython

Section titled “ESP32 not responding after flashing MicroPython”

Causes: Wrong firmware version or flash address.

Solutions:

  1. Erase flash completely: esptool.py erase_flash
  2. Re-flash with correct address: 0x1000 for generic ESP32
  3. Try a different USB port or cable

Causes: MicroPython interpreter uses most available RAM.

Solutions:

  1. Reduce buffer sizes (e.g., smaller JSON documents)
  2. Free memory with gc.collect() periodically
  3. Use the micropython.mem_total() and micropython.mem_free() to monitor
  4. Consider using ESP32-S3 with PSRAM for MicroPython

Causes: The DHT library is not included in all MicroPython builds.

Solutions:

  1. Use a different MicroPython firmware build that includes DHT support
  2. Manually copy the dht.py library to the ESP32 filesystem
  3. Read the DHT sensor directly using the onewire module
  • Use the REPL for exploration: Test sensor readings and pin states interactively before writing a script
  • Save frequently used code as modules: Create reusable .py modules and import them in main.py
  • Monitor memory with gc: gc.collect() and gc.mem_free() help prevent out-of-memory errors
  • Use main.py as boot entry point: MicroPython automatically executes main.py on startup
  • Handle Wi-Fi disconnection gracefully: Use a try-except loop with reconnection logic
  • Avoid MicroPython for timing-critical applications: The interpreter adds jitter; use C/C++ for precise timings
  1. MicroPython brings Python to the ESP32, enabling rapid development and interactive experimentation
  2. Firmware is flashed using esptool or Thonny IDE (recommended for beginners)
  3. The REPL allows live interaction with GPIO, sensors, and Wi-Fi
  4. main.py auto-executes on boot, enabling standalone operation
  5. MicroPython is ideal for prototyping, education, and data logging — but not for production or timing-critical applications