MicroPython Programming on ESP32
MicroPython Programming on ESP32
Overview
Section titled “Overview”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++
Prerequisites
Section titled “Prerequisites”- Basic Python programming knowledge
- An ESP32 development board
- USB-UART driver installed
Key Concepts
Section titled “Key Concepts”What is MicroPython?
Section titled “What is MicroPython?”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
MicroPython vs Arduino C++
Section titled “MicroPython vs Arduino C++”| Aspect | MicroPython | Arduino C++ |
|---|---|---|
| Development Speed | Fast (no compile step) | Slower (compile + upload) |
| Execution Speed | Slower (interpreted) | Fast (compiled native) |
| RAM Usage | Higher (interpreter overhead) | Lower |
| Learning Curve | Low (if Python known) | Moderate (C++ syntax) |
| Library Ecosystem | Growing, but smaller | Very large, mature |
| Debugging | REPL + print statements | Serial print, GDB with JTAG |
| Real-Time Control | Limited (no preemption) | Full (FreeRTOS) |
| File Size | Larger binary (includes interpreter) | Smaller binary |
| Best For | Prototyping, education, data logging | Production, precision timing, complex projects |
Implementation Steps
Section titled “Implementation Steps”Step 1: Install MicroPython Firmware on ESP32
Section titled “Step 1: Install MicroPython Firmware on ESP32”Option A: Using esptool (Command Line)
-
Download the latest MicroPython firmware for ESP32 from micropython.org/download/ESP32_GENERIC/
-
Install esptool:
Terminal window pip install esptool -
Erase the ESP32 flash:
Terminal window esptool.py --chip esp32 --port /dev/cu.usbserial-XXXX erase_flash(Replace
/dev/cu.usbserial-XXXXwith your port) -
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)
- Download and install Thonny IDE from thonny.org
- Connect the ESP32 via USB
- In Thonny, go to Run > Select Interpreter
- Choose MicroPython (ESP32)
- Select the correct port
- Go to Tools > Options > Interpreter
- Click Install or update MicroPython
- Select the ESP32 variant and click Install
- Wait for the installation to complete
Step 2: Connect to the REPL
Section titled “Step 2: Connect to the REPL”Once MicroPython is installed:
-
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
-
You should see the MicroPython banner:
MicroPython v1.21.0 on 2023-10-05; ESP32 module with ESP32Type "help()" for more information.>>> -
Test the REPL:
>>> print("Hello from ESP32!")Hello from ESP32!>>> import machine>>> machine.freq()240000000
Step 3: Blink an LED
Section titled “Step 3: Blink an LED”Create a file named main.py in Thonny (File > New) and save it to the ESP32 (File > Save As > MicroPython Device):
import machineimport 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.
Step 4: Read a Sensor (DHT22)
Section titled “Step 4: Read a Sensor (DHT22)”import machineimport dhtimport time
# DHT22 connected to GPIO 4sensor = 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)Step 5: Connect to Wi-Fi
Section titled “Step 5: Connect to Wi-Fi”import networkimport 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])Step 6: MQTT Publish with MicroPython
Section titled “Step 6: MQTT Publish with MicroPython”Install the umqtt.simple library (available in the MicroPython package repository):
import networkimport timefrom umqtt.simple import MQTTClientimport machine
# Wi-Fi connectionwlan = network.WLAN(network.STA_IF)wlan.active(True)wlan.connect("YourWiFiSSID", "YourWiFiPassword")while not wlan.isconnected(): time.sleep(0.5)
# MQTT setupclient = MQTTClient("esp32-client", "192.168.1.100", port=1883)client.connect()
# Publish a messageclient.publish(b"esp32/test", b"Hello from MicroPython!")print("Message published")
client.disconnect()Verification
Section titled “Verification”- MicroPython REPL responds to Python commands
-
main.pyauto-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
Troubleshooting
Section titled “Troubleshooting”ESP32 not responding after flashing MicroPython
Section titled “ESP32 not responding after flashing MicroPython”Causes: Wrong firmware version or flash address.
Solutions:
- Erase flash completely:
esptool.py erase_flash - Re-flash with correct address:
0x1000for generic ESP32 - Try a different USB port or cable
”MemoryError” when running a script
Section titled “”MemoryError” when running a script”Causes: MicroPython interpreter uses most available RAM.
Solutions:
- Reduce buffer sizes (e.g., smaller JSON documents)
- Free memory with
gc.collect()periodically - Use the
micropython.mem_total()andmicropython.mem_free()to monitor - Consider using ESP32-S3 with PSRAM for MicroPython
No such file or directory: ‘dht’
Section titled “No such file or directory: ‘dht’”Causes: The DHT library is not included in all MicroPython builds.
Solutions:
- Use a different MicroPython firmware build that includes DHT support
- Manually copy the
dht.pylibrary to the ESP32 filesystem - Read the DHT sensor directly using the onewire module
Best Practices
Section titled “Best Practices”- Use the REPL for exploration: Test sensor readings and pin states interactively before writing a script
- Save frequently used code as modules: Create reusable
.pymodules and import them inmain.py - Monitor memory with
gc:gc.collect()andgc.mem_free()help prevent out-of-memory errors - Use
main.pyas boot entry point: MicroPython automatically executesmain.pyon 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
Summary
Section titled “Summary”- MicroPython brings Python to the ESP32, enabling rapid development and interactive experimentation
- Firmware is flashed using esptool or Thonny IDE (recommended for beginners)
- The REPL allows live interaction with GPIO, sensors, and Wi-Fi
main.pyauto-executes on boot, enabling standalone operation- MicroPython is ideal for prototyping, education, and data logging — but not for production or timing-critical applications