IoT with Raspberry Pi 6 and Python
TOP 5 Feb. 10, 2026, 11:30 p.m.

IoT with Raspberry Pi 6 and Python

Welcome to the world of Internet‑of‑Things with the brand‑new Raspberry Pi 6! In this guide we’ll walk through everything you need to turn this tiny computer into a powerful edge device, from setting up the OS to wiring sensors, writing clean Python code, and pushing data to the cloud. Whether you’re a hobbyist building a smart garden or a developer prototyping an industrial monitor, the Pi 6 paired with Python gives you a flexible, low‑cost platform that scales with your imagination.

Why Raspberry Pi 6 Is a Game‑Changer for IoT

The Pi 6 brings a quad‑core Cortex‑A78 processor, up to 8 GB RAM, and built‑in Wi‑Fi 6/BT 5.3, which means faster data handling and more reliable wireless connectivity. Its expanded GPIO header (40 pins plus two extra I²C and SPI buses) lets you attach a wider variety of sensors without multiplexing. Plus, the new USB‑C power input simplifies power management for battery‑or‑solar projects.

From a software perspective, Raspberry Pi OS (formerly Raspbian) now ships with Python 3.12 pre‑installed, and the official gpiozero library has been optimized for the new hardware. This combination reduces latency when reading analog‑to‑digital converters (ADCs) or toggling relays, which is crucial for real‑time IoT applications.

Getting the Pi 6 Ready for IoT Development

Start by flashing the latest Raspberry Pi OS Lite image onto a 16 GB microSD card using Raspberry Pi Imager. Choose the “Lite” version if you prefer a headless setup; it boots directly to the command line, saving precious CPU cycles.

After the first boot, enable SSH and I²C via raspi-config. This gives you remote access and a simple way to talk to most sensors. Don’t forget to expand the filesystem to use the whole SD card—another raspi-config option.

#!/usr/bin/env python3
import subprocess

def enable_interfaces():
    # Enable SSH
    subprocess.run(["sudo", "systemctl", "enable", "ssh"])
    subprocess.run(["sudo", "systemctl", "start", "ssh"])
    # Enable I2C
    subprocess.run(["sudo", "raspi-config", "nonint", "do_i2c", "0"])
    # Expand filesystem
    subprocess.run(["sudo", "raspi-config", "nonint", "do_expand_rootfs"])

if __name__ == "__main__":
    enable_interfaces()

The script above automates the most common post‑install steps, making it easy to spin up multiple Pi 6 units for a fleet deployment.

Reading Sensor Data with Python

One of the first things you’ll want to do is read environmental data. The DHT22 temperature‑humidity sensor is inexpensive and works well with the Pi’s 3.3 V logic. We’ll use the Adafruit_DHT library, which abstracts the low‑level timing required for the sensor.

Connecting the DHT22

  • Pin 1 (VCC) → 3.3 V pin on the Pi
  • Pin 2 (DATA) → GPIO 4 (physical pin 7)
  • Pin 3 (NC) → leave unconnected
  • Pin 4 (GND) → Ground pin

Don’t forget a 10 kΩ pull‑up resistor between VCC and DATA to keep the line stable.

#!/usr/bin/env python3
import Adafruit_DHT
import time

SENSOR = Adafruit_DHT.DHT22
PIN = 4  # GPIO4

def read_sensor():
    humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
    if humidity is not None and temperature is not None:
        print(f"Temp: {temperature:.1f}°C  Humidity: {humidity:.1f}%")
    else:
        print("Failed to retrieve data from sensor")

if __name__ == "__main__":
    while True:
        read_sensor()
        time.sleep(5)

This loop prints a fresh reading every five seconds, which is a solid baseline for logging or triggering actions.

Controlling Actuators: Turning a Relay On and Off

Now that you can sense the world, let’s make the Pi act on it. A 5 V relay module lets you switch higher‑voltage devices—lights, fans, or even a small pump. The Pi’s GPIO pins can safely drive the relay’s input coil when you use a transistor driver circuit or a relay board with built‑in opto‑isolation.

Wiring the Relay Module

  • VCC → 5 V pin (pin 2)
  • GND → Ground (pin 6)
  • IN1 → GPIO 17 (physical pin 11)

With the hardware in place, the gpiozero library makes control trivial.

#!/usr/bin/env python3
from gpiozero import OutputDevice
import time

relay = OutputDevice(17, active_high=False, initial_value=False)

def toggle_relay(duration=2):
    print("Relay ON")
    relay.on()
    time.sleep(duration)
    print("Relay OFF")
    relay.off()

if __name__ == "__main__":
    while True:
        toggle_relay()
        time.sleep(10)

Here the relay stays closed for two seconds, then opens, with a ten‑second pause before the next cycle. You can replace the fixed timing with sensor‑based conditions, such as turning a fan on when temperature exceeds 30 °C.

Sending Data to the Cloud with MQTT

Local processing is great, but the real power of IoT emerges when devices talk to each other or to a central dashboard. MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe protocol designed for constrained networks. We’ll use the open‑source Mosquitto broker, which you can run on the Pi itself or on a remote server.

First, install the client library:

sudo apt-get update
sudo apt-get install -y python3-paho-mqtt

Next, publish the DHT22 readings to a topic called home/garden/temperature. The subscriber could be a Home Assistant instance, a Node‑RED flow, or a simple Python script on your laptop.

#!/usr/bin/env python3
import Adafruit_DHT
import paho.mqtt.client as mqtt
import json
import time

SENSOR = Adafruit_DHT.DHT22
PIN = 4
BROKER = "mqtt.example.com"
TOPIC = "home/garden/temperature"

client = mqtt.Client()
client.connect(BROKER, 1883, 60)

def publish_reading():
    humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
    if humidity is None or temperature is None:
        return
    payload = {
        "temperature": round(temperature, 1),
        "humidity": round(humidity, 1),
        "timestamp": int(time.time())
    }
    client.publish(TOPIC, json.dumps(payload))
    print(f"Published: {payload}")

if __name__ == "__main__":
    while True:
        publish_reading()
        time.sleep(30)

The JSON payload makes it easy for downstream services to parse and visualize the data. You can also add QoS levels or TLS encryption for added reliability and security.

Security Best Practices for Edge Devices

IoT devices are frequent targets for attackers, so hardening your Pi 6 is essential. Start by changing the default pi password and disabling password authentication for SSH in /etc/ssh/sshd_config. Use key‑based login instead.

Next, set up a firewall with ufw to only allow the ports you need—typically 22 for SSH, 1883 for MQTT, and maybe 80/443 if you run a local web UI.

#!/usr/bin/env python3
import subprocess

def harden_system():
    # Update packages
    subprocess.run(["sudo", "apt-get", "update"])
    subprocess.run(["sudo", "apt-get", "upgrade", "-y"])

    # Change default user password (prompted)
    # Disable password auth
    subprocess.run(["sudo", "sed", "-i", "s/^#PasswordAuthentication yes/PasswordAuthentication no/", "/etc/ssh/sshd_config"])
    subprocess.run(["sudo", "systemctl", "restart", "ssh"])

    # Enable UFW and allow needed ports
    subprocess.run(["sudo", "ufw", "default", "deny", "incoming"])
    subprocess.run(["sudo", "ufw", "default", "allow", "outgoing"])
    subprocess.run(["sudo", "ufw", "allow", "22/tcp"])
    subprocess.run(["sudo", "ufw", "allow", "1883/tcp"])
    subprocess.run(["sudo", "ufw", "--force", "enable"])

if __name__ == "__main__":
    harden_system()

Running this script will bring your Pi up to a reasonable security baseline, suitable for both home labs and production prototypes.

Pro tip: Store MQTT credentials in a separate .env file and load them with python-dotenv. This keeps secrets out of version control and makes rotating keys painless.

Real‑World Use Cases

Smart Garden Monitor

Combine the DHT22 sensor with a soil moisture probe (analog output via an MCP3008 ADC) and a relay‑controlled water pump. The Pi reads temperature, humidity, and soil moisture every minute, publishes to MQTT, and automatically waters plants when moisture falls below a threshold. A simple dashboard built in Grafana can display trends and let you manually trigger irrigation.

Home Security Camera Trigger

Attach a PIR motion sensor to GPIO 27 and a USB webcam to the Pi. When motion is detected, a Python script captures a short video clip, saves it locally, and uploads it to an S3 bucket via the boto3 library. An optional push notification (via Pushover or Telegram) alerts you instantly.

#!/usr/bin/env python3
import RPi.GPIO as GPIO
import subprocess
import time
import datetime
import boto3

PIR_PIN = 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)

s3 = boto3.client('s3')
BUCKET = "my-security-uploads"

def capture_video():
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"/tmp/motion_{timestamp}.h264"
    # Record 10 seconds of video
    subprocess.run(["raspivid", "-t", "10000", "-o", filename])
    return filename

def upload_to_s3(filepath):
    s3.upload_file(filepath, BUCKET, filepath.split('/')[-1])
    print(f"Uploaded {filepath} to S3")

def monitor():
    print("Waiting for motion...")
    while True:
        if GPIO.input(PIR_PIN):
            print("Motion detected!")
            video = capture_video()
            upload_to_s3(video)
            time.sleep(30)  # debounce
        time.sleep(0.5)

if __name__ == "__main__":
    try:
        monitor()
    finally:
        GPIO.cleanup()

This script demonstrates how the Pi can act as an edge processor, reducing bandwidth by only sending data when an event occurs.

Industrial Equipment Health Check

In a factory setting, the Pi 6 can read vibration data from an accelerometer (e.g., ADXL345) over SPI, compute RMS values in real time, and publish anomalies to an MQTT topic monitored by a SCADA system. Because the Pi has a more powerful CPU than older models, you can run lightweight machine‑learning inference (TensorFlow Lite) directly on the device to predict equipment failures before they happen.

Performance Tweaks and Optimization

When scaling to dozens of sensors, consider using the asyncio library to avoid blocking I/O. Group sensor reads into coroutines and let the event loop handle them concurrently. This reduces CPU idle time and improves overall throughput.

#!/usr/bin/env python3
import asyncio
import Adafruit_DHT
import aiohttp
import json

SENSOR = Adafruit_DHT.DHT22
PIN = 4
BROKER_URL = "http://mqtt.example.com/publish"

async def read_dht():
    humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
    if humidity is None or temperature is None:
        return None
    return {"temp": temperature, "hum": humidity}

async def publish(session, payload):
    async with session.post(BROKER_URL, json=payload) as resp:
        return await resp.text()

async def main():
    async with aiohttp.ClientSession() as session:
        while True:
            data = await read_dht()
            if data:
                await publish(session, data)
                print(f"Sent {data}")
            await asyncio.sleep(10)

if __name__ == "__main__":
    asyncio.run(main())

Using aiohttp for non‑blocking HTTP requests (or an async MQTT client) keeps the Pi responsive even under heavy sensor load.

Deploying and Managing Multiple Pi 6 Nodes

For larger deployments, leverage BalenaOS or Docker to containerize your Python services. A docker-compose.yml file can spin up a sensor collector, an MQTT bridge, and a local InfluxDB instance on a single Pi, simplifying updates and rollbacks.

# docker-compose.yml
version: "3.8"
services:
  collector:
    image: python:3.12-slim
    volumes:
      - ./collector:/app
    working_dir: /app
    command: ["python", "collector.py"]
    restart: unless-stopped
    privileged: true   # needed for GPIO access
  mqtt:
    image: eclipse-mosquitto
    ports:
      - "1883:1883"
    restart: unless-stopped
  influxdb:
    image: influxdb:2.7
    ports:
      - "8086:8086"
    environment:
      - INFLUXDB_DB=metrics
    restart: unless-stopped

Deploy with a single docker compose up -d command, and you have a self‑contained IoT stack ready to scale across your network.

Conclusion

The Raspberry Pi 6, coupled with Python’s rich ecosystem, offers a versatile foundation for building robust IoT solutions. From basic sensor reads to cloud‑integrated, secure edge applications, the steps outlined here equip you to prototype quickly and scale responsibly. Keep experimenting, secure your devices, and let the Pi’s new performance capabilities inspire the next generation of connected projects.

Share this article