Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 149 ยท Data and the Web

Python for the Internet of Things (IoT)

Use Python for Internet of Things projects - Raspberry Pi with GPIO Zero, Arduino with pyFirmata, ESP32 with MicroPython, and MQTT messaging, with runnable simulations.

The Internet of Things (IoT) is the idea of everyday objects, such as thermostats, door sensors, greenhouse monitors and street lamps, that have a small computer inside and can send data over a network. A typical project has the same four parts: a sensor or actuator that touches the physical world, a device that runs code to read or drive it, a network link and a service that stores the data, shows it or reacts to it.

Python fits well because the programs are short, the libraries are friendly and you can reuse the same language on the device, on a gateway and in the cloud. This lesson shows the three common ways to put Python near hardware, and the messaging pattern (MQTT) that joins devices together.

Note: Hardware code can't run in your browser, so the examples that talk to pins are read-only. Every idea that is plain logic (smoothing sensor data, alert rules, a message broker) comes with a runnable simulation.

Three ways to run Python near hardware

Approach Typical board Python flavor Good for
Single-board computer Raspberry Pi Full CPython on Linux Cameras, dashboards, gateways, anything needing libraries
Microcontroller ESP32, ESP8266, Raspberry Pi Pico MicroPython Cheap battery-powered sensors with Wi-Fi
Computer controlling a board Arduino connected by USB Full Python on the PC, a Firmata sketch on the Arduino Quick experiments and teaching

Raspberry Pi with GPIO Zero

A Raspberry Pi runs Linux, so everything in this course works on it. Its GPIO (general-purpose input/output) pins can be switched on and off or read as inputs. The GPIO Zero library hides the electrical details behind objects such as LED, Button and MotionSensor. It comes preinstalled on Raspberry Pi OS (or sudo apt install python3-gpiozero). Pins are named with their Broadcom (BCM) numbers.

Python
from gpiozero import LED, Button
from signal import pause

led = LED(17)            # an LED (with a resistor) on GPIO 17
button = Button(2)       # a push button on GPIO 2

button.when_pressed = led.on      # event handlers, no polling loop
button.when_released = led.off

pause()                  # keep the program alive and wait for events

Handlers like when_pressed run when the hardware reports a change, which is the same event-driven idea you met in tkinter. To read a value instead, use properties: button.is_pressed, sensor.value. For a temperature sensor, wiring and a bit of library code (for example a DHT22 or a BME280 over I2C) give you a number to work with.

Arduino with pyFirmata

An Arduino runs compiled C++, not Python. The Firmata protocol lets a normal computer control it over USB: you upload the StandardFirmata sketch once (from the Arduino IDE, under File > Examples > Firmata), then drive the pins from Python with the pyfirmata package (pip install pyfirmata).

Python
import time
from pyfirmata import Arduino, util

board = Arduino("COM3")                  # "/dev/ttyACM0" on Linux, "/dev/cu.usbmodem..." on macOS

iterator = util.Iterator(board)          # a thread that keeps reading incoming pin data
iterator.start()

board.analog[0].enable_reporting()       # read analog pin A0
led = board.digital[13]                  # the on-board LED

try:
    while True:
        level = board.analog[0].read()   # a float from 0.0 to 1.0, or None at first
        if level is not None:
            led.write(1 if level > 0.5 else 0)
        time.sleep(0.1)
finally:
    board.exit()

Connect the board's pins with jumper wires, then check the port name in your operating system's device list. The Iterator thread is required, or analog reads stay None. The trade-off is that the computer must stay connected: the Arduino has no program of its own to run.

ESP8266 and ESP32 with MicroPython

MicroPython is a compact reimplementation of Python 3 for microcontrollers. An ESP32 or ESP8266 board with Wi-Fi costs a few dollars, runs for months on a battery in deep sleep and runs the code you put on it by itself.

Flashing MicroPython onto a board takes two steps. Install the flasher with pip install esptool, then download the firmware .bin for your chip from micropython.org and flash it:

TEXT
esptool --chip esp32 erase-flash
esptool --chip esp32 write-flash -z 0x1000 ESP32_GENERIC.bin

(Older esptool versions spell the commands erase_flash and write_flash, and the flash offset differs between chips, so follow the instructions for your board.) After that the board offers a Python prompt over USB serial, and tools such as Thonny, mpremote or rshell copy your main.py to it. A file called main.py runs automatically at every power-up.

Python
# main.py on an ESP32
import time
import network
import dht
from machine import Pin

led = Pin(2, Pin.OUT)
sensor = dht.DHT22(Pin(4))

wlan = network.WLAN(network.STA_IF)      # station mode: join an existing Wi-Fi network
wlan.active(True)
wlan.connect("my-wifi", "my-password")
while not wlan.isconnected():
    time.sleep(0.5)

while True:
    sensor.measure()
    print("temperature:", sensor.temperature(), "humidity:", sensor.humidity())
    led.value(not led.value())           # blink as a heartbeat
    time.sleep(10)

machine and network exist only on MicroPython. Memory is tiny (often a few hundred kilobytes), so keep programs lean, avoid big imports, and read values in small steps.

Cleaning up sensor data (runnable)

Real sensors are noisy. Two small techniques turn raw readings into something you can act on: a moving average to smooth spikes, and hysteresis so a heater doesn't flicker on and off when the temperature hovers around the threshold. The simulation below uses a fake sensor, so it runs anywhere.

Python Smoothing and hysteresis on simulated readings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

MQTT: how devices talk to each other

Wi-Fi sensors rarely call each other directly. Most IoT systems use MQTT (Message Queuing Telemetry Transport), a lightweight publish/subscribe protocol designed for small devices and unreliable links. The roles are:

  • A broker (for example Mosquitto, or a cloud IoT service) receives every message and forwards it.
  • A publisher sends a message to a topic such as home/livingroom/temperature.
  • A subscriber tells the broker which topics it wants. Publishers and subscribers never know about each other.

Topics are slash-separated levels. A subscription may use + to match exactly one level and # to match everything below (at the end only). So home/+/temperature matches the living room and the kitchen, and home/# matches everything in the house. MQTT offers three delivery guarantees called QoS: 0 (at most once), 1 (at least once) and 2 (exactly once). Higher levels cost more traffic.

The most popular Python client is paho-mqtt (pip install paho-mqtt). Version 2 expects you to name the callback API version:

Python
import paho.mqtt.client as mqtt

def on_message(client, userdata, message):
    print(message.topic, message.payload.decode())

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_message = on_message
client.connect("localhost", 1883)                 # a broker on your own machine
client.subscribe("home/+/temperature", qos=1)

client.publish("home/kitchen/temperature", "21.5", qos=1)
client.loop_forever()                             # processes network traffic and callbacks

A tiny broker you can run

You can't open network ports in the browser, but you can model the broker's job: store subscriptions and match each published topic against them. This gives you the topic-matching rules without a network.

Python A miniature publish/subscribe broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last test shows a subtle rule: in real MQTT a/# also matches the parent a, which this miniature broker handles because # returns early only after the a level matched. A real broker also adds retained messages, QoS and last-will messages that announce a device that disappeared.

Safety and good habits

  • Never wire mains voltage (a wall socket) to a hobby board. Use a relay module or a certified smart plug.
  • Protect pins. GPIO pins on a Raspberry Pi run at 3.3 V, so an LED needs a resistor and a 5 V signal can damage the board.
  • Secure the network side. Use unique passwords, TLS (port 8883) for MQTT outside your home network and updated firmware. Keep secrets out of source code, as in Python Security.
  • Plan for failure. Wi-Fi drops. Reconnect, timeout and retry, and use a watchdog timer on microcontrollers so a frozen device restarts itself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Python do you run on an ESP32 microcontroller?

    MicroPython is a small Python 3 implementation made for microcontrollers with limited memory, and it provides the machine and network modules.
  2. 2. What does the Firmata protocol let you do?

    You upload the StandardFirmata sketch, and pyfirmata on the computer sends commands to it over USB.
  3. 3. In MQTT, what does the subscription home/+/temperature match?

    + stands for exactly one level. Use # at the end of a pattern to match every level below.
  4. 4. Why add hysteresis to a thermostat?

    With separate on and off thresholds, small noisy changes around one value no longer flip the output.
  5. 5. What does a GPIO Zero handler such as button.when_pressed = led.on avoid?

    The library calls your function when the hardware reports a change, so your program doesn't have to check constantly.

Summary

  • IoT systems combine sensors, small devices, a network and a service. Python can run on all of these ends.
  • Raspberry Pi runs full Python and GPIO Zero gives it simple objects for pins; pyFirmata drives an Arduino from a PC; MicroPython runs on cheap Wi-Fi microcontrollers such as the ESP32.
  • Smooth noisy readings with a moving average and use hysteresis for on/off decisions.
  • MQTT is a publish/subscribe protocol: devices publish to topics, subscribers use + and # wildcards, and a broker forwards messages.
  • Protect the hardware, the network and your credentials, and plan for dropped connections.

Next: Python in the Cloud, where the same data is sent to AWS, Azure and serverless functions.