Controlling GPIO from a Web Page with Flask
Control a GPIO pin from a simple web page served by the Pi itself, using Flask — a lightweight Python web framework.
You'll need: the LED wiring from Lesson rpi-09, and your Pi connected to your local network.
pip install flaskWith Flask installed, a small script can serve a real web page directly from the Pi, with buttons that trigger GPIO changes:
from flask import Flask
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
@app.route("/on")
def led_on():
GPIO.output(17, GPIO.HIGH)
return "LED is ON"
@app.route("/off")
def led_off():
GPIO.output(17, GPIO.LOW)
return "LED is OFF"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Each @app.route("/path") line maps a URL to a Python function — visiting http://[your-pi's-IP]:5000/on in any browser on your network runs led_on() and returns its text as the page content. host="0.0.0.0" makes the server reachable from other devices on your network, not just the Pi itself; the default would only accept connections from the Pi.
This is a deliberately minimal starting point — a real project would build an actual HTML page with clickable buttons rather than requiring you to type URLs by hand, but the underlying pattern (a URL route triggering a GPIO action) is exactly the same either way, and now you have a Pi controllable from any phone or laptop on your Wi-Fi.