MicroPython Programming with ESP32 and ESP8266 (1)
Introduction
MicroPython is a lightweight implementation of Python designed for microcontrollers. It provides an interactive prompt (REPL) and supports most Python libraries, making it ideal for IoT applications. The ESP32 and ESP8266 microcontrollers are widely used due to their Wi-Fi capabilities and compatibility with MicroPython.
In this guide, we will cover:
- Installing MicroPython on ESP32 and ESP8266.
- Writing and running basic MicroPython programs.
- Using sensors and GPIO control with MicroPython.
Prerequisites
Before proceeding, ensure you have:
- An ESP32 or ESP8266 board.
- A USB cable to connect the board to your computer.
- Python 3.7+ installed on your system.
- Thonny or uPyCraft IDE for writing and uploading MicroPython code.
Step 1: Flashing MicroPython Firmware
To use MicroPython on your ESP32/ESP8266, you need to flash the firmware.
1. Download MicroPython Firmware
Download the latest firmware for your board from the official MicroPython website:
2. Install esptool
Install esptool
, a command-line utility for flashing firmware:
pip install esptool
3. Erase Flash Memory
Before flashing, erase the existing firmware:
esptool.py --port /dev/ttyUSB0 erase_flash
(Replace /dev/ttyUSB0
with the correct port, e.g., COM3
on Windows.)
4. Flash MicroPython
Flash the downloaded MicroPython firmware:
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0x1000 firmware.bin
After flashing, restart the board.
Step 2: Connecting to the MicroPython REPL
The REPL (Read-Eval-Print Loop) allows you to interact with MicroPython.
1. Connect via Serial Terminal
Use a serial terminal like screen
or picocom
(Linux/macOS):
screen /dev/ttyUSB0 115200
Or use Thonny IDE (recommended for beginners) by selecting the MicroPython interpreter.
Step 3: Writing and Uploading MicroPython Code
1. Blink an LED
Create a Python script blink.py
:
from machine import Pin
import time
led = Pin(2, Pin.OUT) # GPIO2 is the onboard LED
while True:
led.value(not led.value())
time.sleep(1)
Upload and run it using Thonny or ampy
:
ampy --port /dev/ttyUSB0 put blink.py
2. Read a Sensor (DHT11 Temperature & Humidity Sensor)
Connect a DHT11 sensor to GPIO4 and use this script:
import dht
import machine
sensor = dht.DHT11(machine.Pin(4))
sensor.measure()
print("Temperature:", sensor.temperature(), "C")
print("Humidity:", sensor.humidity(), "%")
Step 4: Using Wi-Fi on ESP32/ESP8266
Connect to a Wi-Fi network using MicroPython:
import network
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("Your_SSID", "Your_PASSWORD")
while not sta.isconnected():
pass
print("Connected!", sta.ifconfig())
Conclusion
You have successfully set up MicroPython on ESP32/ESP8266 and learned how to:
- Flash the firmware.
- Use the REPL terminal.
- Control GPIOs and read sensor data.
- Connect to Wi-Fi.
Now, you can start building IoT applications with MicroPython!