MicroPython on ESP32: “Lightning-Fast” IoT Programming for Software Developers

Python tutorial - IT technology blog
Python tutorial - IT technology blog

Run Your First ESP32 Code in 5 Minutes

In the past, I used to avoid embedded programming because of messy C++ syntax and memory leaks that were a nightmare to debug. MicroPython has completely changed the game. Now, you can control LEDs or read sensors with just a few lines of clean, concise Python code.

To get started, prepare this basic kit:

  • ESP32 Board: Preferably the DevKit V1 (priced around $3 – $5).
  • Micro-USB Cable: A data-capable cable.
  • Thonny IDE: A lightweight tool that works with MicroPython right out of the box.

Step 1: Flash Firmware – Giving the Chip its “Soul”

Open Thonny, go to Tools > Options > Interpreter and select MicroPython (ESP32). Next, click Install or update MicroPython. Select the correct COM port and the firmware file (.bin) downloaded from micropython.org. This process usually takes less than 30 seconds to complete.

Pro tip: If Thonny doesn’t recognize the board, press and hold the BOOT button on the ESP32 when starting the flash.

Step 2: Writing a Real “Hello World”

Instead of just printing text to a screen, the hardware world says hello by blinking an LED. Copy this code into Thonny:

from machine import Pin
import time

# GPIO 2 is usually connected to the onboard LED on the ESP32
led = Pin(2, Pin.OUT)

while True:
    led.value(1)  # Turn LED ON
    time.sleep(0.5)
    led.value(0)  # Turn LED OFF
    time.sleep(0.5)

Press F5 and see the result. The tiny LED on the board will blink steadily. You’ve officially controlled hardware!

MicroPython vs. Arduino (C++): Why Make the Switch?

I once spent a whole morning just configuring an HTTP library on Arduino. With MicroPython, the same task takes exactly 10 lines of code. The difference lies in deployment speed.

The biggest advantage is the REPL (Read-Eval-Print Loop). You can type commands directly into the Terminal window, and the board executes them immediately. No waiting for compilation, no need to re-flash the entire program. This makes the prototyping process three times faster than traditional methods.

With a Dual Core 240MHz CPU and 520KB RAM, the ESP32 has plenty of power to run the Python runtime for Smart Home projects or light industrial gateways.

Real-World Project: Temperature Monitoring Web Server

Let’s upgrade to a more practical application: Reading data from a DHT11 sensor and pushing it to a Web interface hosted by the ESP32 itself.

Hardware Connection

  • DHT11 VCC connects to the 3.3V pin of the ESP32.
  • DHT11 GND connects to the GND pin.
  • DHT11 DATA connects to GPIO 4.

Web Server Script

import network
import socket
import dht
from machine import Pin

# WiFi Configuration
ssid = 'Your_WiFi_Name'
password = 'Your_WiFi_Password'

# Network Connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

while not wlan.isconnected():
    pass

print('Your IP:', wlan.ifconfig()[0])
sensor = dht.DHT11(Pin(4))

def get_html(temp, hum):
    return f"""HTTP/1.1 200 OK\nContent-Type: text/html\n\n
    <html><body><h1>ESP32 Monitor</h1>
    <p>Temperature: {temp}C</p><p>Humidity: {hum}%</p>
    </body></html>"""

# Initialize Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    conn, addr = s.accept()
    sensor.measure()
    response = get_html(sensor.temperature(), sensor.humidity())
    conn.send(response)
    conn.close()

Run the script, open your phone’s browser, and visit the IP address shown in Thonny. You will see real-time room temperature updates. A basic Smart Home system is born!

3 “Critical” Tips to Avoid Fried Chips and Crashed Code

After many bricked boards and unexplained errors, I’ve learned three valuable lessons:

  1. Manual RAM Management: MicroPython has a Garbage Collector, but with limited memory, you should proactively call gc.collect() after processing large JSON strings or long HTML blocks.
  2. Never Leave Loops “Hungry”: Never use while True: pass. Always add time.sleep_ms(10). This gives the CPU a break, reducing chip temperature by 5-10°C and significantly saving battery.
  3. Exception Handling: IoT connections drop frequently. Wrap your connection code in a try...except block. Otherwise, a single WiFi loss will cause your entire device to hang and require a manual restart.

Scaling Up: Moving Toward Professional Systems with MQTT

A Web Server is only suitable for simple needs. If you want to manage hundreds of devices, you need MQTT. This is the standard protocol for ESP32 to communicate with platforms like Home Assistant or AWS IoT.

My experience working on warehouse monitoring projects is to use the umqtt.simple library. Instead of having clients access the ESP32 directly, the board proactively pushes data to a Broker (like Mosquitto). This makes the system more secure and prevents it from being overloaded when multiple users view the data at once.

Hardware programming isn’t scary. With MicroPython, every mistake can be fixed with a Reset button. Start today!

Share: