Disclosure: We earn a commission from some links on this page. Details
Build Home Assistant room sensors with a Raspberry Pi (no soldering)
Temperature, humidity and real CO2 readings in Home Assistant from plug-in SparkFun sensors on a Raspberry Pi, plus an optional status screen and power monitoring.
- Difficulty
- Intermediate
- Time
- 2 to 3 hours
Drafted with AI assistance, fact-checked and approved by RackedPrice. Checked Nov 24, 2026.
This project puts plug-in sensors on a Raspberry Pi and sends their readings to Home Assistant: temperature, humidity and air pressure, plus real CO2 if you add the second sensor. Then you can graph a room, get a "open a window" alert when the air gets stuffy, or run a fan automatically.
Everything uses Qwiic, SparkFun's plug-in connector for small sensors. The cable only fits one way and there's no soldering. Every sensor and plug-in board here is made by SparkFun.
How it fits together: the Pi reads the sensors every minute and sends the readings to Home Assistant over MQTT, a simple messaging system Home Assistant supports out of the box. Home Assistant adds the sensors by itself, so there's no YAML to write.
- How Qwiic sensors talk to a Raspberry Pi over I2C
- How MQTT and discovery get readings into Home Assistant
- How to run a Python script in a virtual environment
- How to start a script at boot with systemd
Give the Pi a Qwiic port
- The Qwiic pHAT sits on the pin header and gives you several Qwiic ports, a screw terminal for power and a button. Get this one if the Pi lives in an open case or on a shelf. SparkFun notes it may not seat fully in some tight cases.
- Short on room? The Qwiic SHIM slips onto the header without soldering and gives you one Qwiic port. Chain the sensors off each other from there.
- Plug a cable from the pHAT into the BME280, and if you have the CO2 sensor, a second cable from the BME280's other port into it. Qwiic boards pass the connection along, so the order doesn't matter.
- Put the sensors at least a cable's length from the Pi. A Pi warms the air right around it, and a sensor sitting on top of it reads a few degrees high.
Prepare the Pi
- Write Raspberry Pi OS Lite (64-bit) to a card with Raspberry Pi Imager, setting a username, password and SSH in its settings. Our Pi-hole guide walks through it. One Pi can do both jobs.
- Log in with SSH and turn on I2C, the connection Qwiic uses: run
sudo raspi-configand switch it on under Interface Options (Raspberry Pi's guide). - Check the Pi sees the sensors:
sudo apt install -y i2c-tools, theni2cdetect -y 1. You should see one address in the grid for each sensor you plugged in. An empty grid means a loose cable or I2C still off. - Raspberry Pi OS only lets pip install into a virtual environment, so make one:
python3 -m venv ~/sensors - Install SparkFun's libraries for the BME280 and SCD40, and the MQTT library:
~/sensors/bin/pip install sparkfun-qwiic-bme280 sparkfun-qwiic-scd4x paho-mqtt
Turn on MQTT in Home Assistant
- In Home Assistant, install the Mosquitto broker app. The MQTT integration's docs call it the recommended setup.
- Start it, then add the MQTT integration when Home Assistant offers it under Settings, Devices and services.
- Make a Home Assistant user just for the sensors (Settings, People, Users), with a long password. The sensor box logs in to MQTT with it.
The sensor script
Save this on the Pi as room_sensor.py in your home folder (nano ~/room_sensor.py, paste, then Ctrl+O and Ctrl+X). Change the four settings at the top. It works with just the BME280, and adds CO2 when the SCD40 is plugged in.
#!/usr/bin/env python3
"""Room sensor: reads a SparkFun BME280 (and an SCD40, if one is plugged in) and sends the readings to
Home Assistant over MQTT. Home Assistant adds the sensors by itself (MQTT discovery)."""
import json
import socket
import time
import paho.mqtt.client as mqtt
import qwiic_bme280
import qwiic_scd4x
BROKER = "homeassistant.local" # your Home Assistant's address
USER, PASSWORD = "sensors", "change-me"
ROOM = "office"
EVERY = 60 # seconds between readings
node = f"{socket.gethostname()}_{ROOM}".replace("-", "_")
state = f"rooms/{node}/state"
SENSORS = [ # reading, name, device class, unit
("temperature", "Temperature", "temperature", "°C"),
("humidity", "Humidity", "humidity", "%"),
("pressure", "Pressure", "pressure", "hPa"),
("co2", "CO2", "carbon_dioxide", "ppm"),
]
bme = qwiic_bme280.QwiicBme280()
if not bme.begin():
raise SystemExit("BME280 not found: check the cable, and that I2C is switched on")
scd = qwiic_scd4x.QwiicSCD4x()
has_co2 = scd.is_connected() and scd.begin() # no SCD40 plugged in: CO2 is left out
device = {"identifiers": [node], "name": f"{ROOM.title()} sensor", "manufacturer": "DIY"}
def announce(client, userdata, flags, reason_code, properties):
"""Tell Home Assistant about each sensor, every time we (re)connect."""
for key, name, cls, unit in SENSORS:
if key == "co2" and not has_co2:
continue
config = {"name": name, "unique_id": f"{node}_{key}", "state_topic": state,
"device_class": cls, "unit_of_measurement": unit, "state_class": "measurement",
"value_template": "{{ value_json.%s }}" % key, "device": device}
client.publish(f"homeassistant/sensor/{node}/{key}/config", json.dumps(config), retain=True)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.username_pw_set(USER, PASSWORD)
client.on_connect = announce
client.connect(BROKER, 1883)
client.loop_start()
co2 = None
while True:
if has_co2 and scd.read_measurement():
co2 = scd.get_co2()
reading = {"temperature": round(bme.temperature_celsius, 1),
"humidity": round(bme.humidity, 1),
"pressure": round(bme.pressure / 100, 1)} # pascals to hPa
if co2 is not None:
reading["co2"] = co2
client.publish(state, json.dumps(reading))
time.sleep(EVERY)Try it: ~/sensors/bin/python ~/room_sensor.py. Within a minute, a new device called "Office sensor" shows up in Home Assistant under the MQTT integration, with its readings. The script uses MQTT discovery, which is how Home Assistant knows what each reading is. Press Ctrl+C to stop it.
Start it automatically
- Make a service so it starts at boot and restarts if it ever stops:
sudo nano /etc/systemd/system/room-sensor.service - Paste this, changing
yournameto your username in both places:
[Unit]
Description=Room sensor for Home Assistant
Wants=network-online.target
After=network-online.target
[Service]
User=yourname
ExecStart=/home/yourname/sensors/bin/python /home/yourname/room_sensor.py
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target- Turn it on:
sudo systemctl enable --now room-sensor. Check on it any time withsystemctl status room-sensor.
Make it useful
- SparkFun's docs give the SCD40 a range of 0 to 40,000 ppm, most accurate from 400 to 2,000 ppm, which is where a normal room sits. Rising CO2 is stuffy air, so it's a good trigger for an "open a window" notification or a fan.
- Building more than one? Give each Pi a different
ROOMand you get one device per room.
A status screen (optional)
- SparkFun's Qwiic OLED is a small black-and-white screen that chains on like the sensors. A common use is showing the room's readings, the Pi's address and, if it also runs Pi-hole, the blocked count. SparkFun has a Python package for it.
Whole-home power monitoring (optional)
- SparkFun's Non-Invasive Current Sensor ADE7953, sold alone or as a kit with the clamp, measures the AC current through a wire with a clamp around it, without cutting anything. SparkFun's docs say this board measures current only, not voltage, so the watts you get are an estimate based on your normal mains voltage.
- Safety first: the wires worth measuring are usually inside your breaker panel, and some parts in there stay live even with the main breaker off. If you're not qualified, have an electrician fit the clamp.
- Heads up: SparkFun's examples use its own microcontroller board, not a Pi, so expect to adapt the code.
What to skip
- Switching lamps or heaters with a relay board. SparkFun makes one, but mains wiring needs real care, and a ready-made smart plug does the same job safely.
Stuck?
- "BME280 not found": check the cable is clicked in at both ends, and that I2C is on (
i2cdetect -y 1should show it). - Nothing shows up in Home Assistant: check the MQTT username and password, and that
BROKERis your Home Assistant's address.systemctl status room-sensorshows the error. - The temperature reads high: move the sensor further from the Pi.
About the SparkFun links: they're ours. SparkFun has no price feed, so check the price on its page.
Parts used in this guide
Already have the gear? You don't need anything here.
What you can skip: Already run Home Assistant? Skip the Green and point the sensors at the one you have. Any Raspberry Pi with the 40-pin header works as the sensor box, so an older Pi in a drawer is fine.
| Home Assistant Green Runs Home Assistant itself, ready to plug in. The simplest way in if you don't have Home Assistant yet. | |
| Raspberry Pi 5 2GB The sensor box. Reading sensors is light work, so the cheapest Pi 5 is plenty. | |
| Raspberry Pi 27W USB-C power supply The official supply for the Pi 5. | |
| Qwiic pHAT v2.0 Sits on the Pi's pins and gives you four plug-in Qwiic ports. No soldering. | |
| BME280 Atmospheric Sensor (Qwiic) Temperature, humidity and air pressure on one small board. | |
| SCD40 CO2 sensor (Qwiic) optional Measures real CO2, the best sign a room needs fresh air. Worth it for a bedroom or home office. | |
| Qwiic Cable Kit Cables in several lengths. The long ones keep the sensor away from the Pi's warmth. | |
| Qwiic SHIM optional Instead of the pHAT, if your case has no room on top. One port; chain the sensors from it. | |
| Qwiic OLED 1.3in optional For the status screen. | |
| Non-Invasive Current Sensor kit (ADE7953) optional For power monitoring. Have an electrician fit the clamp. |