Control an LED from your phone with a Raspberry Pi web server

Turn your Raspberry Pi into a small web server with Python and Flask. Any phone or laptop on the same Wi-Fi can open its page, dim the LED with buttons and see how warm the Pi's processor is.
  • Level:Beginner
  • Duration: 50 min
  • Ages 11+
  • Platform: Raspberry Pi

What you'll need

Control an LED from your phone with a Raspberry Pi web server – EEMENTOR STEM™ lesson

Every website you visit runs on a computer somewhere, called a web server. Your Raspberry Pi can be one too. In this last lesson of the starter path you write a tiny web server in Python with Flask. When you open the Pi's address on your phone, it sends back a page with buttons. Tap a button and the LED on the breadboard dims or brightens, and the page shows the temperature of the Pi's processor. You learn how web addresses, pages and routes work, and how the Pi dims an LED with PWM. This is where the Pi really shines compared with an Arduino: it runs a full web server with just a few lines of code.

What you'll learn

  • What a web server is, and how a browser asks it for a page
  • How Flask connects web addresses (routes) to Python functions
  • How to fill values into a web page with format()
  • How PWM dims an LED with gpiozero's PWMLED
  • How to find the Pi on your network, and why to keep it on your home network only

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS on a microSD card (see the first lesson) and its USB-C power supply
  • 1 LED and a 220 Ω resistor (ESP32 IoT Starter Kit)
  • A phone, tablet or laptop on the same Wi-Fi as the Pi
  • Breadboard (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires, to go from the Pi's pins to the breadboard. If you don't have any, plug a female-female and a male-male Dupont wire from the ESP32 IoT Starter Kit together.

Look after your Pi: the GPIO pins work at 3.3 V. Never connect 5 V (or the 5V pins) to a GPIO pin, never connect a GPIO pin straight to GND or to 3.3 V with a plain wire, never connect a 3V3 or 5V pin to GND, and always shut the Pi down and unplug it before you change the wiring. A single wrong wire can damage the Pi for good.

Wiring

The same LED circuit as in the blink lesson:

Breadboard wiring diagram: Control an LED from your phone with a Raspberry Pi web server
Breadboard view. Check each connection against the wiring table below.

Build it step by step

Plug in all the parts first, then add the wires in this order. In each picture the new wires are bright and the ones from earlier steps are faded. Click a picture to see it larger.

Step 1 of 2: GND (pin 9) from the Pi to the blue rail
Step 1. GND (pin 9) from the Pi to the blue rail
Step 2 of 2: LED and resistor: GPIO 17 (pin 11)
Step 2. LED and resistor: GPIO 17 (pin 11)
From To
GPIO 17 (pin 11) 220 Ω resistor → LED long leg (+)
LED short leg (−) The blue (−) rail of the breadboard
The blue (−) rail GND (pin 9)

Install Flask

Open the Terminal on the Pi and type these two lines, pressing Enter after each (it asks for your password; if it asks "Do you want to continue?", type Y and press Enter):

sudo apt update
sudo apt install python3-flask

If it says Flask is already the newest version, that is fine too.

The program

Open Thonny (Raspberry menu → Programming → Thonny), paste the program into a new file, save it in your home folder as web_led.py, and click the green Run button. Press the red Stop button (or Ctrl+C) to stop it. gpiozero is already installed on Raspberry Pi OS.

# web_led.py: a web page on the Pi that sets the LED's brightness and shows the CPU temperature
from flask import Flask, redirect
from gpiozero import PWMLED, CPUTemperature

app = Flask(__name__)
led = PWMLED(17)                 # GPIO 17 (pin 11); a PWMLED can be dimmed
cpu = CPUTemperature()

PAGE = """<!doctype html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Raspberry Pi</title>
<style>
body {{ font-family: Arial, sans-serif; text-align: center; background: #F6F8FC; color: #1B3A7B; }}
a {{ display: inline-block; margin: 6px; padding: 16px 22px; border-radius: 14px;
     background: #1B3A7B; color: #fff; text-decoration: none; font-size: 20px; }}
</style></head><body>
<h1>My Raspberry Pi</h1>
<p>The LED is at {level} %</p>
<p>CPU temperature: {temp} &deg;C</p>
<a href="/led/0">Off</a><a href="/led/25">25 %</a><a href="/led/50">50 %</a><a href="/led/100">On</a>
</body></html>"""

@app.route("/")
def home():
    return PAGE.format(level=round(led.value * 100), temp=round(cpu.temperature, 1))

@app.route("/led/<int:level>")
def set_led(level):
    level = max(0, min(level, 100))  # keep it between 0 and 100
    led.value = level / 100          # PWMLED wants 0.0 (off) to 1.0 (full)
    print("LED set to", level, "%")
    return redirect("/")             # show the main page again

app.run(host="0.0.0.0", port=5000)   # 0.0.0.0: other devices on the network can open it

Try it

  1. Run the program. The Shell shows a few lines from Flask, including Running on http://127.0.0.1:5000 and another address. You can ignore the red warning that this is a development server. Each time a page loads, Flask prints a line in red too: that is just its log, not an error (a "404" for favicon.ico is normal).
  2. On the Pi itself, open the web browser and go to http://localhost:5000. You see your page with four buttons.
  3. Tap 50 %: the LED glows at half brightness, the page reloads and shows "The LED is at 50 %". Try the other buttons.
  4. Now use your phone. Find the Pi's address: type hostname -I in a new Terminal window and use the first address, for example 192.168.1.42. On the phone, connected to the same Wi-Fi, open http://192.168.1.42:5000 (with your Pi's address). Or try http://mypi.local:5000 with the hostname you chose in the first lesson (this works on most iPhones and laptops, but not on every Android phone; then use the numbers).
  5. Type an address by hand: /led/10 after the port, for example http://192.168.1.42:5000/led/10. The LED goes to 10 %.
  6. Press Stop in Thonny. The page no longer opens, and the LED switches off.

What you should see

Thonny Shell with Flask running on port 5000 and the request log, next to a phone showing the page: LED at 50 %, CPU temperature, buttons Off, 25 %, 50 % and On.

How it works

How it works: the phone requests /led/50, Flask runs set_led(50) and redirects to /, home() sends the page; PWM waves show 25 %, 50 % and 100 % at 100 times a second.

When you open http://192.168.1.42:5000/led/50, the browser sends a request to the computer at address 192.168.1.42, to port 5000 (a kind of door number; Flask uses 5000), asking for /led/50. Flask looks at that path and finds the function whose @app.route matches: "/led/<int:level>" matches /led/50 and hands over 50 as level. The function sets the LED and answers with a redirect: "now go to /". The browser does, and the function home() sends back the page.

The page itself is just text in HTML, the language of web pages, stored in PAGE. PAGE.format(level=..., temp=...) puts the current values where {level} and {temp} are. The style rules in the page also use curly brackets, so they are doubled ({{ }}): that tells format() to leave them alone.

A GPIO pin can only be fully on or fully off. To dim the LED, PWMLED uses PWM (pulse-width modulation): it switches the pin on and off 100 times a second. At 25 % the pin is on for a quarter of each cycle. That is far too fast for your eyes to see, so the LED just looks dimmer.

host="0.0.0.0" tells Flask to answer requests from other devices on your network, not just from the Pi itself. Keep it that way: on your home or school network only. Never set up your router so that the whole internet can reach this program, because anyone could then switch your LED, and Flask's built-in server isn't made to be safe on the open internet.

Try this next

  • Add a button to the circuit, as in the button lesson, and show on the page whether it is pressed.
  • Control the three traffic-light LEDs from the traffic lights lesson with one button each on the page.
  • Make the page refresh by itself every 5 seconds, so the temperature stays up to date: add <meta http-equiv="refresh" content="5"> to the head of the page.
  • Start the program automatically when the Pi starts: ask an adult to type crontab -e (without sudo) and add the line @reboot python3 /home/yourname/web_led.py (with your username). While it runs in the background, running the program from Thonny gives "GPIO busy" or "Address already in use", so remove the line again when you want to change the program.
  • Next lesson: fade an LED and mix colours with an RGB LED.

Troubleshooting

  • "No module named flask": run sudo apt install python3-flask in the Terminal, then run the program again.
  • The phone can't open the page: the phone must be on the same Wi-Fi as the Pi (not on mobile data, not on a guest network). Use the address from hostname -I, with http:// and :5000 at the end. Some school networks block devices from seeing each other.
  • "Address already in use": the program is still running from before, or it was started automatically at boot (see crontab in Try this next). Press Stop in Thonny, wait a few seconds and run it again.
  • The LED doesn't dim, only on and off: check that the program uses PWMLED, not LED.
  • "GPIO busy" or "pin already in use": another program (maybe an earlier run that is still going) is using the pin. Press Stop in Thonny, close other programs that use GPIO, and run it again.
  • Always shut down properly: click the Raspberry menu → Shutdown, or type sudo shutdown now, and wait until the green light stops flashing before you unplug the power. Pulling the plug while the Pi is working can damage the files on the microSD card.