In this project your Pico W becomes a tiny web server. Open its address on any phone or computer on your home Wi-Fi and you get a page with two buttons that switch an LED on and off. It's the starting point for anything you want to control from a browser, and it teaches Wi-Fi, how a web request works, and how to serve several visitors at once.
What you need
- A Raspberry Pi Pico W or Pico 2 W, with headers, and a USB cable that carries data
- One LED of any colour, and one 330 Ω resistor (orange, orange, brown)
- A breadboard, two jumper wires, and Thonny on your computer
- Your Wi-Fi network name and password. The Pico W only uses 2.4 GHz Wi-Fi. Most home routers offer 2.4 GHz alongside 5 GHz, often under the same name.
Step 1: wire the LED
- Unplug the Pico W and push it into the breadboard across the centre gap.
- Connect the 330 Ω resistor from GP15, pin 20, to an empty row.
- Put the LED's long leg in that row and its short leg in another row.
- Jumper the short leg's row to GND, pin 18.
That gives the LED about (3.3 − 2) ÷ 330 ≈ 4 mA for a red LED, which is bright enough and well within what a Pico pin can supply. Use the LED resistor calculator for other colours.
Step 2: the code
Paste this into a new file in Thonny. Change SSID and PASSWORD to your Wi-Fi details, keeping the quotes. Save it to the Pico W as main.py, then click Run.
import network, asyncio, time
from machine import Pin
SSID = "your-wifi-name"
PASSWORD = "your-wifi-password"
lamp = Pin(15, Pin.OUT) # the LED you're switching, on GP15
board_led = Pin("LED", Pin.OUT)
lamp.off()
# ---- connect to Wi-Fi ----
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm=0xa11140) # turn off Wi-Fi power saving so the page responds quickly
wlan.connect(SSID, PASSWORD)
print("Connecting", end="")
for _ in range(20):
if wlan.isconnected():
break
board_led.toggle()
print(".", end="")
time.sleep(1)
if not wlan.isconnected():
raise RuntimeError("Wi-Fi failed, status %d" % wlan.status())
try:
ip = wlan.ipconfig("addr4")[0] # newer MicroPython
except AttributeError:
ip = wlan.ifconfig()[0] # older MicroPython
board_led.on()
print("\nOpen http://%s in a browser on the same network" % ip)
# ---- the web page ----
def page():
state = "ON" if lamp.value() else "OFF"
return """<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pico switch</title><style>body{font-family:sans-serif;text-align:center;padding:2em}
button{font-size:1.5em;padding:.6em 1.6em;margin:.3em;border-radius:.4em}</style></head>
<body><h1>The light is %s</h1>
<form method="post" action="/on"><button>Turn on</button></form>
<form method="post" action="/off"><button>Turn off</button></form>
</body></html>""" % state
def response(status, body="", extra=""):
head = ("HTTP/1.1 %s\r\nContent-Type: text/html; charset=utf-8\r\n"
"Content-Length: %d\r\nConnection: close\r\n%s\r\n" % (status, len(body), extra))
return (head + body).encode()
# ---- the web server ----
async def handle(reader, writer):
try:
line = await asyncio.wait_for(reader.readline(), 5) # e.g. "POST /on HTTP/1.1"
while True: # skip the headers
h = await asyncio.wait_for(reader.readline(), 5)
if h in (b"\r\n", b"\n", b""):
break
parts = line.decode().split(" ")
method, path = (parts[0], parts[1]) if len(parts) > 2 else ("", "")
print(method, path)
if method == "POST" and path in ("/on", "/off"):
lamp.value(1 if path == "/on" else 0)
writer.write(response("303 See Other", extra="Location: /\r\n"))
elif method == "GET" and path == "/":
writer.write(response("200 OK", page()))
else:
writer.write(response("404 Not Found", "Not found"))
await writer.drain()
except Exception as e: # a browser that connects and sends nothing times out here
print("Connection closed:", repr(e))
finally:
writer.close()
await writer.wait_closed()
async def main():
await asyncio.start_server(handle, "0.0.0.0", 80)
while True:
await asyncio.sleep(3600)
asyncio.run(main())
Thonny's shell shows dots while the Pico W connects, then a line such as Open http://192.168.1.42. Type that address into a browser on a phone or computer on the same Wi-Fi network. Tap the buttons and the LED follows. The Pico's own LED stays on while it's connected.
How it works
- Joining Wi-Fi.
network.WLAN(network.STA_IF)is the Pico W's Wi-Fi in "station" mode, the same as a phone joining a network. The code waits up to 20 seconds to connect. Turning off power saving withpm=0xa11140is Raspberry Pi's advice for web servers, because the radio's sleep mode makes the page slow to answer. - A web request. When you open the page, the browser sends text such as
GET / HTTP/1.1, followed by header lines and a blank line. The server reads the first line to see what's wanted, skips the headers, and sends back a status line, its own headers, a blank line and the page. - Why the buttons use POST. GET requests are meant only to fetch things, and browsers sometimes fetch links in advance to be quick. If
/onwere a plain link, a browser could switch your LED on without you tapping it. The buttons send POST requests instead, and the server only changes the LED for a POST. - The 303 redirect. After a button press the server replies "303 See Other" and sends the browser back to
/. That shows the new state, and refreshing the page won't press the button again. - Several visitors at once. Browsers often open extra connections in advance and leave them idle. A simple server that handles one connection at a time would get stuck waiting on one of these.
asynciolets the Pico handle each connection as its own task, and the 5-second timeout closes connections that never send anything.
main.py without removing your Wi-Fi password.Troubleshooting
- "Wi-Fi failed, status -3": the password is wrong. Passwords are case-sensitive.
- "Wi-Fi failed, status -2": the network wasn't found. Check the name and that your router has 2.4 GHz switched on. If it still won't connect, add
network.country("GB")(with your own country code) just beforewlan.active(True), so the Pico W uses your country's Wi-Fi channels. - "Wi-Fi failed, status -1" or 0 to 2: the connection failed or timed out. Move closer to the router and try again.
- The page won't load: make sure your phone is on the same Wi-Fi, not mobile data or a guest network. Some routers keep guest devices apart.
- The address changes: your router hands out addresses, and may give the Pico W a different one after a while. Most routers let you reserve an address for a device in their settings.
Take it further
- Add a reading to the page, such as the temperature from the temperature logger project, and refresh it every few seconds with
<meta http-equiv="refresh" content="5">. - Switch something bigger, such as a low-voltage fan or LED strip, with a transistor or MOSFET. Our guide to transistors as switches shows how. Leave mains-powered equipment alone unless you use a properly certified smart plug.
- Add more buttons and pins: each needs a new path, such as
/fan-on, in theifstatement.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.