Switch on the desk lamp from the sofa, run the fan for exactly 20 minutes, or light the aquarium every morning at 7:30 while you are still asleep. In this project the Raspberry Pi becomes a smart relay panel: a web page on your phone controls two relays, each relay can run a countdown timer, and you can add daily schedules. Everything is saved in a file, and the Pi starts the panel by itself when it boots, so a power cut doesn't make it forget your settings.
What you'll learn
- How a relay module works, and why its inputs are active-low
- How to power the relay coils from 5V while the Pi's 3.3 V pins control them safely
- How a background thread runs timers and schedules while Flask answers your phone
- How to save settings to a JSON file so they survive a reboot
- How to start a program automatically at boot with a systemd service
What you need
- Raspberry Pi 4 Model B with Raspberry Pi OS and its USB-C power supply, connected to your Wi-Fi
- 2-channel relay module (ESP32 IoT Starter Kit)
- For the two test loads: the 9 V battery, 1 white LED, 1 red LED and 2 resistors of 560 Ω (ESP32 IoT Starter Kit)
- Breadboard and jumper wires, including female-to-female wires for the relay module's pins (ESP32 IoT Starter Kit)
- A small screwdriver for the relay's screw terminals
- A phone or computer on the same Wi-Fi network
New to Flask? Do Control an LED from your phone with a Raspberry Pi web server first. If Flask isn't installed yet, run sudo apt install python3-flask in a terminal.
Low voltage only. The relays on the module are labelled for mains voltage, but a breadboard project is not a safe place for it. In this project the relays only ever switch the 9 V battery from the kit, or another battery or USB supply of 12 V or less. Never connect a relay to a wall socket, a lamp cable or anything plugged into the mains. That work belongs to a qualified electrician.
Look after your Pi: the GPIO pins work at 3.3 V. Never connect 5 V or the 9 V battery to a GPIO pin, keep the battery circuit completely separate from the Pi, and shut the Pi down before you change the wiring.
Wiring
The relay module has two groups of pins. The input header (GND, IN1, IN2, VCC) is the control side that the Pi talks to. The small 3-pin header next to it (JD-VCC, VCC, GND) normally has a plastic jumper joining JD-VCC to VCC. Pull that jumper off: you are going to power the relay coils (JD-VCC) from 5V and the input side (VCC) from 3.3 V. Then use female-to-female or female-to-male wires:

| Relay module pin | Raspberry Pi pin |
|---|---|
| VCC (input header) | 3V3 (pin 1) |
| JD-VCC (3-pin header, jumper removed) | 5V (pin 2) |
| GND (input header) and GND (3-pin header) | GND (pin 9, through the blue − rail) |
| IN1 | GPIO 17 (pin 11) |
| IN2 | GPIO 27 (pin 13) |
The test loads. Each relay has three screw terminals: COM (common), NO (normally open, connected to COM only while the relay is on) and NC (normally closed). Build two little battery lamps that the relays switch:
| From | To |
|---|---|
| 9 V battery + | COM of relay 1 and COM of relay 2 |
| NO of relay 1 | 560 Ω resistor → white LED long leg; LED short leg → 9 V battery − |
| NO of relay 2 | 560 Ω resistor → red LED long leg; LED short leg → 9 V battery − |
The battery circuit is not connected to the Pi at all: the relay contacts are just a switch. Later you can replace the LEDs with any low-voltage gadget, such as a 5 V USB lamp (cut into a spare USB cable only with an adult's help) or a 12 V LED strip with its own adapter.
The program
Save the program as relay_panel.py in your home folder and run it in Thonny. The Shell prints a line every time a relay switches. On your phone, open http://<your-pi>.local:5000, for example http://raspberrypi.local:5000, or use the Pi's IP address from hostname -I.
# Smart relay panel: two relays, a web page, countdown timers and daily schedules
from gpiozero import OutputDevice
from flask import Flask, jsonify, request
from datetime import datetime
import json, os, threading, time
STATE_FILE = os.path.expanduser("~/relay_state.json")
# The relay module's inputs are active-low: a LOW pin switches the relay ON
relays = {
"1": OutputDevice(17, active_high=False, initial_value=False),
"2": OutputDevice(27, active_high=False, initial_value=False),
}
lock = threading.Lock()
state = {
"names": {"1": "Desk lamp", "2": "Fan"},
"on": {"1": False, "2": False},
"until": {"1": None, "2": None}, # countdown end time (seconds since 1970) or None
"schedules": [], # {"ch": "1", "on": "07:30", "off": "08:00"}
}
def save():
tmp = STATE_FILE + ".tmp"
with open(tmp, "w") as f:
json.dump(state, f, indent=2)
os.replace(tmp, STATE_FILE) # write the whole file, then swap it in
def load():
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
state.update(json.load(f))
for ch, relay in relays.items(): # put the relays back the way they were
relay.value = state["on"][ch]
def switch(ch, on, until=None):
relays[ch].value = on
state["on"][ch] = on
state["until"][ch] = until if on else None
print(f"{datetime.now():%H:%M:%S} {state['names'][ch]} {'ON' if on else 'OFF'}")
def tick(now=None):
"""Called every second: ends countdowns and runs the daily schedules."""
now = now or datetime.now()
hhmm = now.strftime("%H:%M")
changed = False
with lock:
for ch, end in state["until"].items():
if end and now.timestamp() >= end:
switch(ch, False)
changed = True
if now.second == 0: # check the schedules once a minute
for s in state["schedules"]:
if s["on"] == hhmm and not state["on"][s["ch"]]:
switch(s["ch"], True); changed = True
elif s["off"] == hhmm and state["on"][s["ch"]]:
switch(s["ch"], False); changed = True
if changed:
save()
def clock():
while True:
tick()
time.sleep(1 - time.time() % 1) # wake up at the start of every second
app = Flask(__name__)
@app.route("/")
def page():
return PAGE
@app.route("/api/state")
def api_state():
with lock:
left = {ch: max(0, round(end - time.time())) if end else 0 for ch, end in state["until"].items()}
return jsonify({**state, "left": left})
@app.route("/api/<ch>/<action>", methods=["POST"])
def api_switch(ch, action):
if ch not in relays:
return "No such relay", 404
with lock:
if action == "on":
switch(ch, True)
elif action == "off":
switch(ch, False)
elif action == "timer": # on now, off after N minutes
minutes = max(1, min(720, int(request.form.get("minutes", 10))))
switch(ch, True, time.time() + minutes * 60)
else:
return "Unknown action", 400
save()
return api_state()
@app.route("/api/schedule", methods=["POST"])
def api_schedule():
s = {k: request.form[k] for k in ("ch", "on", "off")}
if s["ch"] not in relays:
return "No such relay", 404
try:
for t in (s["on"], s["off"]):
datetime.strptime(t, "%H:%M")
except ValueError:
return "Use times like 07:30", 400
with lock:
state["schedules"].append(s)
save()
return api_state()
@app.route("/api/schedule/<int:i>", methods=["DELETE"])
def api_unschedule(i):
with lock:
if 0 <= i < len(state["schedules"]):
state["schedules"].pop(i)
save()
return api_state()
PAGE = """<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">
<title>Relay panel</title>
<style>body{font-family:sans-serif;max-width:480px;margin:auto;padding:12px}
.card{border:1px solid #ccc;border-radius:12px;padding:12px;margin:10px 0}
button{font-size:16px;padding:8px 14px;margin:4px}.on{color:#1E9E5A;font-weight:bold}</style>
<h1>Relay panel</h1><div id=cards></div>
<div class=card><b>Daily schedule</b><br>
Relay <select id=sch><option>1</option><option>2</option></select>
on <input id=son type=time value=07:30> off <input id=soff type=time value=08:00>
<button onclick=addSchedule()>Add</button><ul id=list></ul></div>
<script>
async function post(url, body) { const r = await fetch(url, {method: "POST", body}); show(await r.json()); }
function timer(ch) { const f = new FormData(); f.append("minutes", document.getElementById("m" + ch).value); post(`/api/${ch}/timer`, f); }
function addSchedule() { const f = new FormData(); f.append("ch", sch.value); f.append("on", son.value); f.append("off", soff.value); post("/api/schedule", f); }
async function unschedule(i) { const r = await fetch("/api/schedule/" + i, {method: "DELETE"}); show(await r.json()); }
function show(s) {
cards.innerHTML = ["1", "2"].map(ch => `<div class=card><b>${s.names[ch]}</b>
<span class=${s.on[ch] ? "on" : ""}>${s.on[ch] ? "ON" : "off"}</span>
${s.left[ch] ? ` · off in ${Math.ceil(s.left[ch] / 60)} min` : ""}<br>
<button onclick="post('/api/${ch}/on')">On</button><button onclick="post('/api/${ch}/off')">Off</button>
<input id=m${ch} type=number value=10 min=1 max=720 style=width:60px> min
<button onclick=timer('${ch}')>Timer</button></div>`).join("");
list.innerHTML = s.schedules.map((x, i) => `<li>Relay ${x.ch}: on ${x.on}, off ${x.off}
<button onclick=unschedule(${i})>Delete</button></li>`).join("");
}
fetch("/api/state").then(r => r.json()).then(show);
setInterval(() => fetch("/api/state").then(r => r.json()).then(show), 5000);
</script>"""
if __name__ == "__main__":
load()
threading.Thread(target=clock, daemon=True).start()
app.run(host="0.0.0.0", port=5000)
Start it automatically at boot
A smart switch is no use if you have to open Thonny after every power cut. A systemd service tells Raspberry Pi OS to start the program at boot and to restart it if it ever crashes. Stop the program in Thonny first, then type whoami in a terminal to see your user name. Create the service file:
sudo nano /etc/systemd/system/relay-panel.service
Paste this, replacing YOURNAME (three times) with your user name:
[Unit]
Description=Smart relay panel
After=network-online.target
Wants=network-online.target
[Service]
User=YOURNAME
WorkingDirectory=/home/YOURNAME
ExecStart=/usr/bin/python3 /home/YOURNAME/relay_panel.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
Save with Ctrl+O, Enter and Ctrl+X, then switch it on:
sudo systemctl daemon-reload
sudo systemctl enable --now relay-panel
systemctl status relay-panel
The status shows active (running). Reboot the Pi with sudo reboot: after about half a minute the panel works again, and any relay that was on is switched back on. To read the program's messages, use journalctl -u relay-panel -f. To stop the service while you edit the program, use sudo systemctl stop relay-panel.
What you should see
The page shows a card for each relay with On, Off and Timer buttons. Press On and you hear the relay click, its little LED on the module lights up, and the white LED lights. Type 1 in the minutes box and press Timer: the card says "off in 1 min", and a minute later the relay clicks off. Add a schedule a couple of minutes from now and watch it switch on and off by itself. The page refreshes every 5 seconds, so a second phone sees the same state.

How it works

The relay. A relay is a switch moved by an electromagnet. When current flows through its coil, the magnet pulls the contact from NC over to NO and you hear the click. The coil needs about 70 mA at 5 V, far more than a GPIO pin can give, so the module has a small circuit for each channel: the Pi's pin only lights the LED inside an optocoupler, and the optocoupler switches a transistor that drives the coil.
Active-low. On this kind of module the optocoupler LED sits between VCC and the IN pin. Current flows, and the relay switches on, when the IN pin is pulled LOW. That's why the program uses OutputDevice(17, active_high=False, initial_value=False): gpiozero turns "on" into a LOW pin for you, and keeps the relay off when the program starts.
Why the jumper comes off. If VCC were 5 V, a GPIO pin that is "off" at 3.3 V would still leave about 1.7 V across the optocoupler's LED, and on some modules that is enough to keep the relay from letting go. With VCC at 3.3 V, a HIGH pin means exactly 0 V across the LED, so the relay always switches off, while JD-VCC still gives the coils their 5 V.
The clock thread. Flask spends its time waiting for your phone, so the timers and schedules run in a second thread. clock() wakes up at the start of every second and calls tick(), which switches off any relay whose countdown has ended. At second 0 of each minute it compares the time, such as "07:30", with every schedule. A Lock makes sure the web page and the clock never change the state at the same moment.
Saved state. Every change is written to relay_state.json. The program first writes a temporary file and then swaps it in with os.replace(), so a power cut in the middle of saving can't leave a half-written file. At start-up, load() reads the file and puts the relays back as they were. Countdowns are stored as a clock time, so a timer that ended while the Pi was off is finished the moment it starts again.
Try this next
- Give the relays your own names: change
"names"inrelay_state.jsonwhile the service is stopped. - Add weekdays to the schedules, for example only Monday to Friday, with
now.weekday(). - Switch a relay with the motion sensor from the motion alarm lesson: light on for 2 minutes after someone walks past.
- Keep going with the next project: Build an ultrasonic radar with a live web display.
Troubleshooting
- The relay never clicks: check that JD-VCC goes to 5V (pin 2) and that the module's GND is connected to the Pi. Without the coil supply, the little input LED may light but the relay stays silent.
- The relay switches on but never off: the jumper is probably still on, so VCC is 5 V. Take it off and connect VCC to 3V3 as in the table.
- Both relays click when the Pi boots: that's normal for a moment, before the program sets the pins. If a gadget must never switch on by itself, connect it to NC and NO the other way round, or only plug it in after start-up.
- The page doesn't open: the phone must be on the same Wi-Fi. Try the IP address instead of the .local name, and check that the program or the service is running.
-
The service fails: run
journalctl -u relay-panel -e. "No such file" means the path or the user name in the service file is wrong. -
A schedule never runs: check the Pi's clock with
date. It sets itself from the internet, so it needs Wi-Fi after every boot.