How to Build a Budget Smart Thermostat with a Raspberry Pi in One Weekend
Ever walked into a house that feels like a sauna in July and an ice box in December? I’ve been there—my own living room once hit 78 °F while I was trying to binge a new series, and the heater kicked on the next day like it was auditioning for a fire‑drill. A cheap, smart thermostat can save you money, keep the house comfy, and give you a tiny taste of home‑automation glory. The best part? You can pull it together with a Raspberry Pi, a few everyday parts, and a weekend’s worth of elbow grease.
What You Need
Parts List
- Raspberry Pi (any model with Wi‑Fi will do; I used a Pi Zero W because it’s tiny and cheap)
- 5 V 2 A power supply for the Pi
- DS18B20 waterproof temperature sensor (digital, easy to read)
- 4.7 kΩ pull‑up resistor (for the sensor)
- 2‑channel relay board (to switch heating and cooling)
- Small 12 V AC‑DC adapter (to power the relay)
- Breadboard and jumper wires
- Optional: small LCD screen (16×2 I2C) if you want a local readout
- Enclosure (a 3D‑printed case or a repurposed project box works fine)
Tools
- Soldering iron (or a good set of dupont connectors if you prefer a solder‑free build)
- Wire cutter/stripper
- Screwdriver set
- Laptop with a fresh Raspberry Pi OS image (I use Raspberry Pi Imager)
Step 1: Get the Pi Ready
First things first, flash the latest Raspberry Pi OS onto a micro‑SD card. I like the “Lite” version because it’s lean and boots fast. Insert the card, plug in the power, and connect the Pi to your home Wi‑Fi. If you’re new to headless setup, enable SSH before you boot and use raspi-config to turn on the interface.
Once you’re in, update everything:
sudo apt update && sudo apt upgrade -y
Install the Python libraries we’ll need:
sudo apt install python3-pip
pip3 install gpiozero w1thermsensor flask
gpiozero makes handling the relay pins a breeze, w1thermsensor talks to the DS18B20, and flask will give us a tiny web dashboard.
Step 2: Wire the Temperature Sensor
The DS18B20 is a digital sensor that talks over a single wire. Connect its red wire to 3.3 V, black to a ground pin, and the yellow (data) to GPIO 4 (pin 7). Slip the 4.7 kΩ resistor between the data line and 3.3 V – this pulls the line high so the Pi can read it.
Enable the 1‑Wire interface on the Pi:
sudo raspi-config
Navigate to Interfacing Options → 1‑Wire and enable it. Reboot, then check that the sensor shows up:
cat /sys/bus/w1/devices/w1_bus_master1/10-xxxx/w1_slave
You should see a line ending in “YES” and a temperature reading in thousandths of a degree.
Step 3: Hook Up the Relays
The relay board lets the Pi control the HVAC system safely. Each channel has a VCC, GND, and IN pin. Connect VCC to 5 V (from the Pi’s 5 V pin), GND to ground, and the IN pins to two free GPIOs—say GPIO 17 for heating and GPIO 27 for cooling.
Safety note: The relays are just switches; they don’t handle the high voltage of your furnace or AC unit directly. Use the relays to control a low‑voltage control line that your thermostat already uses, or have a qualified electrician wire the contacts for you.
Step 4: Write the Control Script
Create a new Python file, smart_thermostat.py. Below is a stripped‑down version that reads the temperature, compares it to a set point, and flips the relays accordingly.
#!/usr/bin/env python3
from gpiozero import OutputDevice
from w1thermsensor import W1ThermSensor
from flask import Flask, request, jsonify
import time
# Configurable parameters
SET_POINT = 22.0 # Desired temperature in Celsius
HYSTERESIS = 0.5 # Prevents rapid toggling
# GPIO pins for relays
heat_relay = OutputDevice(17, active_high=False, initial_value=False)
cool_relay = OutputDevice(27, active_high=False, initial_value=False)
sensor = W1ThermSensor()
app = Flask(__name__)
def control_loop():
while True:
temp_c = sensor.get_temperature()
# Simple dead‑band control
if temp_c < SET_POINT - HYSTERESIS:
heat_relay.on()
cool_relay.off()
elif temp_c > SET_POINT + HYSTERESIS:
heat_relay.off()
cool_relay.on()
else:
heat_relay.off()
cool_relay.off()
time.sleep(30) # Check every 30 seconds
@app.route('/set', methods=['POST'])
def set_point():
global SET_POINT
data = request.get_json()
if 'temp' in data:
SET_POINT = float(data['temp'])
return jsonify({'status':'ok','new_set_point':SET_POINT})
return jsonify({'status':'error','msg':'missing temp'}), 400
@app.route('/status')
def status():
return jsonify({
'temp_c': sensor.get_temperature(),
'set_point': SET_POINT,
'heating': heat_relay.is_active,
'cooling': cool_relay.is_active
})
if __name__ == '__main__':
import threading
t = threading.Thread(target=control_loop, daemon=True)
t.start()
app.run(host='0.0.0.0', port=5000)
Save the file, make it executable, and set it to run at boot with crontab -e:
@reboot /usr/bin/python3 /home/pi/smart_thermostat.py &
Now you have a tiny web API at http://<pi_ip>:5000. You can query /status or POST a new temperature to /set. I built a simple mobile shortcut that hits the API, so I can change the set point from my phone without opening a browser.
Step 5: Add a Local Display (Optional)
If you like seeing the temperature at a glance, hook up a 16×2 I2C LCD. Install the lcd library:
pip3 install RPLCD
Add a few lines to the script to update the screen inside the control_loop. It’s a nice touch and makes the thermostat feel more “real”.
Step 6: Enclose and Test
Mount the Pi, sensor, and relay board inside your chosen enclosure. Drill a small hole for the sensor’s cable to reach the room you want to monitor. Secure the power adapters, and label the relay wires so you know which is heating and which is cooling.
Before you connect to the furnace, do a dry run: power the Pi, watch the /status endpoint, and manually trigger the relays with a Python REPL:
from gpiozero import OutputDevice
heat = OutputDevice(17, active_high=False)
cool = OutputDevice(27, active_high=False)
heat.on() # should click the relay
cool.off()
If the clicks sound right and the furnace’s control line responds, you’re good to go. Turn the system on, set a comfortable temperature, and let the Pi do its thing. In my first weekend test, the house settled at 21 °C within an hour and stayed there without the furnace cycling wildly.
Why This Works for a Budget Build
- Low cost: All parts total under $30, especially if you already have a Pi.
- Open source: No vendor lock‑in; you can tweak the code any way you like.
- Scalable: Add more sensors for different rooms, or integrate with Home Assistant later.
I built this for my own apartment because the landlord’s thermostat was stuck at 20 °C and never adjusted. After a weekend of soldering and a few cups of coffee, I finally had a thermostat that listened to me, not the building’s old wiring.
A Few Tips From the Field
- Mind the power: The Pi and relay board draw a few hundred milliamps. Use a quality power supply; cheap adapters can cause random reboots.
- Use a case with ventilation: The Pi can get warm, especially when the Wi‑Fi antenna is tucked away. A small vent or a heat‑sink helps.
- Add a watchdog: If the Pi crashes, the HVAC could stay on forever. A simple hardware watchdog timer or a UPS with auto‑shutdown can save you from a frozen thermostat.
With these steps, you’ve turned a modest Raspberry Pi into a smart thermostat that saves energy, keeps you comfy, and gives you a solid DIY win to brag about at the next tech meetup. Happy hacking, and enjoy the perfect temperature!
#smart #raspberrypi #diy
#thermostat #homeautomation #budget
- → Building a Low‑Power IoT Magnetic Field Monitor with an Embedded Hall Sensor @sensorinsights
- → Build a Modular Smart Light Switch with Sensor Blocks @sensorblocks
- → How to Build a Reliable Proximity Detector for Home IoT with the HC‑SR04 @sensorcraft
- → Step-by-step Guide to Building a Low-Power CPLD-Based IoT Sensor Node @epldinsights
- → Step‑by‑Step Guide: Integrating IoT Sensors with Power System Protection Relays @relaywatchdog