Definition: MicroPython is a lightweight Python 3 implementation for microcontrollers, enabling complex hardware control, data processing, and network communication for tasks like IoT applications, sensor monitoring, and automation.
Key Use Cases: Building IoT systems, real-time sensor data processing, and networked embedded applications with resource-constrained devices.
Prerequisites: Familiarity with Python programming, basic microcontroller concepts (e.g., GPIO, I2C), and introductory knowledge of networking (e.g., HTTP, MQTT).
What: MicroPython allows users to write Python scripts on microcontrollers to control hardware (e.g., sensors, actuators), process data, and communicate over networks, leveraging Python’s simplicity for embedded systems.
Why: It enables rapid development of complex embedded applications with low power consumption, supporting IoT and real-time tasks without the complexity of C/C++.
Where: Applied in smart home devices, environmental monitoring systems, and industrial IoT for tasks like remote sensing or device control.
MicroPython runs an optimized Python interpreter on microcontrollers, supporting advanced features like multitasking, file systems, and network stacks within memory constraints (e.g., 32-512 KB RAM).
Scripts interact with hardware via protocols like I2C, SPI, or UART, and process data using lightweight algorithms suited for low compute power.
Networking capabilities (e.g., Wi-Fi, MQTT) enable IoT applications, allowing devices to send/receive data to/from servers or other devices.
Key Components:
Microcontroller: Devices like ESP32 or Raspberry Pi Pico with GPIO, ADC, and communication interfaces.
MicroPython Interpreter: Executes scripts with a REPL, file system, and libraries for hardware (e.g., machine) and networking (e.g., network, urequests).
Hardware Interfaces:
GPIO/ADC: For digital/analog input/output.
I2C/SPI: For sensor/actuator communication.
Networking: Wi-Fi or Bluetooth for data exchange, often using protocols like HTTP or MQTT.
Data Processing: Lightweight filtering or aggregation for real-time applications.
Common Misconceptions:
Misconception: MicroPython is too slow for real-time tasks.
Reality: Optimized code and hardware acceleration (e.g., ESP32’s dual-core) enable fast execution for many tasks.
Misconception: MicroPython supports all Python libraries.
Reality: Only a subset of standard libraries and specific MicroPython modules are available due to resource limits.
- System Overview: The diagram shows a MicroPython script executed on a microcontroller, interacting with hardware, processing data, and sending results over a network.
- Component Relationships: The interpreter orchestrates hardware control, data processing, and network communication for integrated outputs.
# MicroPython script for ESP32: Read temperature sensor (DHT11) and send data via MQTTfrommachineimportPinimportdhtimportutimeimportnetworkimportujsonfromumqtt.simpleimportMQTTClient# Wi-Fi credentialsSSID="your_ssid"PASSWORD="your_password"# MQTT configurationMQTT_BROKER="broker.hivemq.com"CLIENT_ID="esp32_sensor"TOPIC=b"sensor/temperature"# Sensor configurationdht_pin=Pin(4,Pin.IN)# DHT11 on GPIO 4sensor=dht.DHT11(dht_pin)# Connect to Wi-Fidefconnect_wifi():wlan=network.WLAN(network.STA_IF)wlan.active(True)ifnotwlan.isconnected():print("Connecting to Wi-Fi...")wlan.connect(SSID,PASSWORD)whilenotwlan.isconnected():utime.sleep(1)print("Wi-Fi connected:",wlan.ifconfig())# Connect to MQTT brokerdefconnect_mqtt():client=MQTTClient(CLIENT_ID,MQTT_BROKER)client.connect()print("Connected to MQTT broker")returnclient# Read and filter sensor data (simple moving average)defread_temperature(samples=5):temps=[]for_inrange(samples):try:sensor.measure()temp=sensor.temperature()temps.append(temp)utime.sleep(0.5)exceptOSErrorase:print("Sensor error:",e)iftemps:returnsum(temps)/len(temps)# Moving averagereturnNone# Main loopconnect_wifi()mqtt_client=connect_mqtt()whileTrue:temp=read_temperature()iftempisnotNone:payload=ujson.dumps({"temperature":temp})mqtt_client.publish(TOPIC,payload)print(f"Published: {payload}")else:print("Failed to read temperature")utime.sleep(10)# Publish every 10 seconds
- Step-by-Step Setup:
1. Hardware: Connect an ESP32 board with a DHT11 temperature sensor to GPIO 4 (with a pull-up resistor if needed).
2. Install MicroPython:
- Download ESP32 MicroPython firmware (.bin) from micropython.org.
- Flash using esptool.py: esptool.py --port /dev/ttyUSB0 write_flash -z 0x1000 firmware.bin.
3. Install Libraries: Copy umqtt/simple.py from MicroPython’s micropython-lib to the board using Thonny or ampy.
4. Install Tools: Use Thonny IDE (thonny.org) or ampy for file transfer (pip install adafruit-ampy).
5. Configure Wi-Fi: Update SSID and PASSWORD in the script.
6. Save and Run:
- Save code as main.py.
- Upload to ESP32 using Thonny or ampy --port /dev/ttyUSB0 put main.py.
- Reset the board to run (monitor output via Thonny or serial terminal at 115200 baud).
- Code Walkthrough:
- Uses dht library to read temperature from a DHT11 sensor.
- Connects to Wi-Fi using network.WLAN and to an MQTT broker with umqtt.simple.
- Filters sensor data with a moving average to reduce noise.
- Publishes temperature data as JSON to an MQTT topic every 10 seconds.
- Common Pitfalls:
- Incorrect DHT11 wiring or missing pull-up resistor causing read errors.
- Wi-Fi connection failures due to incorrect credentials or weak signal.
- Missing umqtt library or incompatible MQTT broker configuration.