Projects / Web control for GPIO

Web control for GPIO

Intermediate2.5 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. Pi 4ON

    Wire the relays and sensor

    With the Pi off.

  2. Pi 4

    Install Flask and the libraries

    Use a virtual environment.

  3. Pi 4ON

    Test the relays in Python

    Click each one.

  4. Pi 4

    Run the app

    With the password variable set.

  5. Pi 4

    Open it in a browser

    http://pi-address:8000.

  6. Pi 4

    Test the login

    Wrong password is refused.

  7. Pi 4

    Run it as a service

    At boot.

In short

How do you build a web control for GPIO?

A Flask app lets you switch relays and see sensor values from any browser on your network. You need Raspberry Pi 4 Model B (4 GB), Relay module 4-channel 5 V, DHT22 Sensor, Resistor 10 kΩ, SanDisk microSD card 32 GB (A1, Class 10) and Raspberry Pi 27 W USB-C power supply. It takes 7 steps and about 150 minutes.

Level
Intermediate
Time
About 150 min
Parts
6

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Relay module IN1 to IN4Pi GPIO5, GPIO6, GPIO13, GPIO19Relay inputs (3.3 V logic)
Relay module VCC and GNDPi 5V and GNDCoil power
DHT22 dataPi GPIO4, with 10 k to 3V3Sensor signal
DHT22 VCC and GNDPi 3V3 and GNDPower
Relay contactsLow-voltage loads only, such as a 12 V fan or lampThe things you control

Code

Raspberry Pi OS (Bookworm or newer) with Python 3. Install the pieces with sudo apt install python3-flask python3-gpiozero python3-libgpiod, and pip install adafruit-circuitpython-dht in a virtual environment. The page is protected by HTTP Basic login, and the password comes from an environment variable so it is never written in the code or saved in a repository. This is plain HTTP, so use it only on a home network you trust and never open its port to the internet; if you want remote access, use a VPN. Switching is done with POST requests only, so a link or a crawler cannot flip a relay by loading a page. Use the relays only for low-voltage loads, or have a qualified electrician wire any mains device in a proper enclosure. Relays start off after a reboot, which is the safe state for most loads. To run it at boot, make a systemd service that sets the PANEL_PASSWORD in an Environment line of a file only you can read.

# Web control panel: switch four relays and read a DHT22. Run with:  PANEL_PASSWORD=choose-your-own python3 panel.py
import os
from flask import Flask, request, Response, redirect
from gpiozero import OutputDevice
import adafruit_dht, board

PASSWORD = os.environ.get("PANEL_PASSWORD")
if not PASSWORD:
    raise SystemExit("Set the PANEL_PASSWORD environment variable first")

app = Flask(__name__)
relays = [OutputDevice(pin, active_high=False, initial_value=False) for pin in (5, 6, 13, 19)]   # most relay boards are active-low
dht = adafruit_dht.DHT22(board.D4)

@app.before_request
def check_login():
    auth = request.authorization
    if not auth or auth.username != "admin" or auth.password != PASSWORD:
        return Response("Login needed", 401, {"WWW-Authenticate": 'Basic realm="Panel"'})

@app.route("/")
def index():
    try:
        t, h = dht.temperature, dht.humidity
        reading = "%.1f C, %.0f %%" % (t, h)
    except Exception:
        reading = "sensor busy, refresh"
    rows = ""
    for i, r in enumerate(relays):
        state = "ON" if r.value else "OFF"
        rows += ('<form method="post" action="/relay/%d"><button>Relay %d: %s</button></form>' % (i, i + 1, state))
    return "<h1>Panel</h1><p>%s</p>%s" % (reading, rows)

@app.route("/relay/<int:n>", methods=["POST"])
def toggle(n):
    if 0 <= n < len(relays):
        relays[n].toggle()
    return redirect("/")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Open the page without a loginRefused
Click a relay buttonRelay clicks and the label changes
DHT22 readingTemperature and humidity shown
RebootRelays start off

If it does not work

Relay works backwards

Change active_high.

DHT22 errors

Normal now and then; refresh, and check the 10 k pull-up.

Page does not open

Check the Pi address and port 8000.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the web control for GPIO?

Raspberry Pi 4 Model B (4 GB), Relay module 4-channel 5 V, DHT22 Sensor, Resistor 10 kΩ, SanDisk microSD card 32 GB (A1, Class 10) and Raspberry Pi 27 W USB-C power supply.

How long does the web control for GPIO take to build?

About 150 minutes for a intermediate maker, in 7 steps.

How do I know the web control for GPIO works?

Open the page without a login: Refused. Click a relay button: Relay clicks and the label changes. DHT22 reading: Temperature and humidity shown.

Relay works backwards: what should I check?

Change active_high.

DHT22 errors: what should I check?

Normal now and then; refresh, and check the 10 k pull-up.

Page does not open: what should I check?

Check the Pi address and port 8000.