Smartlight: control a light from your browser
One of the most satisfying starter home-automation projects is controlling a physical light from a web page. In this post you will build exactly that: a lightweight PHP web interface hosted on your Raspberry Pi that triggers a relay to switch a light on or off. The whole project costs a few euros and takes an afternoon to put together.
Once set up, the controls are accessible from any device on your local network at http://<YOUR_RPI_HOSTNAME>.local/index.php.
What you need
- Raspberry Pi (any model with GPIO pins)
- Single-channel 5 V relay module
- Jumper wires
- A light or appliance within the relay’s rated load
Safety note: If switching mains voltage (230 V / 120 V AC), keep mains wiring well away from the Pi and use a relay module with adequate insulation. If you are not comfortable with mains electricity, switch a 12 V DC lamp instead — same demonstration, much lower risk.
Step 1 — Install required packages
sudo apt-get update
sudo apt-get install python3-dev python3-rpi.gpio apache2 php libapache2-mod-php
Step 2 — Allow Apache to use GPIO
Apache runs as www-data, which cannot access GPIO by default. Add a targeted sudoers rule — avoid giving www-data blanket root access:
sudo visudo
www-data ALL=(root) NOPASSWD: /home/pi/lighton.py, /home/pi/lightoff.py
Step 3 — Create the GPIO scripts
lighton.py — closes the relay circuit:
#!/usr/bin/python3
import RPi.GPIO as GPIO
RELAY_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RELAY_PIN, GPIO.OUT)
GPIO.output(RELAY_PIN, GPIO.HIGH)
lightoff.py — opens the relay circuit:
#!/usr/bin/python3
import RPi.GPIO as GPIO
RELAY_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RELAY_PIN, GPIO.OUT)
GPIO.output(RELAY_PIN, GPIO.LOW)
sudo chmod a+x /home/pi/lighton.py /home/pi/lightoff.py
Step 4 — Create the web interface
cd /var/www/html
sudo nano index.php
<html>
<head>
<meta charset="UTF-8" />
<title>Smartlight</title>
</head>
<?php
if (isset($_POST['LightON'])) { exec("sudo /home/pi/lighton.py"); }
if (isset($_POST['LightOFF'])) { exec("sudo /home/pi/lightoff.py"); }
?>
<form method="post">
<button name="LightON">ON</button>
<button name="LightOFF">OFF</button>
</form>
</html>
Step 5 — Wire the relay and restart Apache
- VCC → Pin 2 (5 V)
- GND → Pin 6 (GND)
- IN (signal) → Pin 12 (GPIO 18, BCM)
sudo systemctl restart apache2
Open http://<your-pi-hostname>.local/index.php from any device on your network. Clicking ON/OFF triggers an audible click from the relay and controls your light. For more Raspberry Pi projects, browse the blog.