ESP32 and MicroPython: Getting Sensor Data to the Cloud
MicroPython makes IoT firmware development faster and more readable. How to collect sensor readings on an ESP32 and publish them to MQTT and a REST API backend.
ESP32 and MicroPython: Getting Sensor Data to the Cloud
MicroPython brings Python to microcontrollers, making IoT firmware development accessible to anyone who knows Python. Combined with the ESP32's built-in WiFi, MicroPython is an excellent choice for sensor nodes that need to connect to cloud services.
Why MicroPython Over Arduino C++?
MicroPython wins when your team knows Python better than C++, you need to iterate quickly, and the computation fits within MicroPython's performance envelope. For IoT sensor nodes that read a sensor every 30 seconds and publish to MQTT, MicroPython is more than fast enough.
Arduino C++ wins when maximum performance is required, lowest possible power consumption is critical, or memory is extremely constrained.
Flashing MicroPython onto ESP32
pip install esptool
esptool.py --chip esp32 --port COM3 erase_flash
esptool.py --chip esp32 --port COM3 write_flash -z 0x1000 esp32-v1.23.0.binUse Thonny IDE for file management and the REPL.
Connecting to WiFi (boot.py)
import network, timedef connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(ssid, password)
timeout = 15
while not wlan.isconnected() and timeout > 0:
time.sleep(1); timeout -= 1
return wlan.isconnected()
`
Reading Sensors
import dht, machinesensor = dht.DHT22(machine.Pin(4))
adc = machine.ADC(machine.Pin(34))
adc.atten(machine.ADC.ATTN_11DB) # 0-3.3V range
def read_sensors():
sensor.measure()
raw_moisture = adc.read()
moisture = max(0, min(100, (4095 - raw_moisture) 100 // (4095 - 1500)))
return {
'temperature': sensor.temperature(),
'humidity': sensor.humidity(),
'moisture': moisture
}
`