Quick answer: to run a web server on a Raspberry Pi Pico W with MicroPython, flash the Pico W MicroPython firmware and connect to Wi-Fi with network.WLAN(network.STA_IF). Then serve pages with asyncio.start_server() (or a plain socket loop) on port 80. Read the request's first line to decide what to do, for example GET /led/on → Pin("LED").on(), and reply with HTTP/1.1 200 OK, a Content-Type header and your HTML. Open the IP address the Pico prints in any browser on the same network. The complete server below switches the onboard LED, shows the chip temperature, and has a JSON endpoint for other programs.
| You need | Notes |
|---|---|
| Raspberry Pi Pico W or Pico 2 W | The plain Pico has no Wi-Fi |
| MicroPython firmware for the Pico W | Install MicroPython on the Pico W |
| Thonny (or VS Code + mpremote) | To edit and run files on the board |
| 2.4 GHz Wi-Fi | The Pico W's radio doesn't support 5 GHz |
| Optional: LED + 220 Ω resistor on GP15 | Any GPIO works; the onboard LED needs no wiring |
1. Connect to Wi-Fi
Create secrets.py on the Pico so credentials stay out of your main code:
# secrets.py
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"import network, time
import secrets
def connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm=0xa11140) # disable Wi-Fi power saving: faster, more reliable replies
wlan.connect(secrets.SSID, secrets.PASSWORD)
for _ in range(20):
if wlan.status() < 0 or wlan.status() >= 3: # error or got IP
break
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError("Wi-Fi failed, status {}".format(wlan.status()))
print("Connected, open http://{}".format(wlan.ifconfig()[0]))
return wlanStatus 3 means connected with an IP address. Negative values are errors (−1 general failure, −2 network not found, −3 wrong password).
2. The complete web server
Save as main.py (next to secrets.py) and run it. It uses asyncio, so the server stays responsive and you can add background tasks later.
import network, time, json, machine, asyncio
import secrets
led = machine.Pin("LED", machine.Pin.OUT)
temp_adc = machine.ADC(4)
# RP2040 internal temperature sensor
def chip_temp_c():
volts = temp_adc.read_u16() * 3.3 / 65535
return 27 - (volts - 0.706) / 0.001721
# formula from the RP2040 datasheet
def page():
state = "ON" if led.value() else "OFF"
return """<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pico W</title><style>body{{font-family:sans-serif;text-align:center;margin-top:40px}}
a{{display:inline-block;padding:14px 28px;margin:8px;background:#2563eb;color:#fff;border-radius:8px;text-decoration:none}}</style></head>
<body><h1>Pico W web server</h1><p>LED is <b>{}</b></p>
<a href="/led/on">LED ON</a><a href="/led/off">LED OFF</a>
<p>Chip temperature: <b>{:.1f} °C</b></p><p><a href="/api">JSON</a></p></body></html>""".format(state, chip_temp_c())
async def handle(reader, writer):
try:
request_line = await reader.readline()
while await reader.readline() not in (b"\r\n", b""):
# skip headers
pass
parts = request_line.decode().split()
path = parts[1] if len(parts) > 1 else "/"
if path == "/led/on":
led.on()
elif path == "/led/off":
led.off()
if path == "/api":
body = json.dumps({"led": led.value(), "temp_c": round(chip_temp_c(), 1)})
ctype = "application/json"
elif path in ("/", "/led/on", "/led/off"):
body, ctype = page(), "text/html"
else:
writer.write(b"HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\nNot found")
await writer.drain()
return
header = "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nConnection: close\r\n\r\n".format(ctype)
writer.write(header.encode())
# MicroPython streams take bytes
writer.write(body.encode())
await writer.drain()
except Exception as e:
print("Request error:", e)
finally:
writer.close()
await writer.wait_closed()
def connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm=0xa11140)
wlan.connect(secrets.SSID, secrets.PASSWORD)
for _ in range(20):
if wlan.status() < 0 or wlan.status() >= 3:
break
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError("Wi-Fi failed, status {}".format(wlan.status()))
print("Open http://{}".format(wlan.ifconfig()[0]))
async def main():
connect()
await asyncio.start_server(handle, "0.0.0.0", 80)
while True:
# room for background tasks
await asyncio.sleep(5)
asyncio.run(main())Open the printed address on your phone or computer. The buttons switch the LED, and the page reloads with the new state and temperature. Visit /api to get {"led": 1, "temp_c": 27.4}, handy for scripts, Node-RED or Home Assistant.
Make the page update itself
Reloading the whole page to see a new temperature is clunky. Add a few lines of JavaScript that fetch /api every two seconds and update the numbers in place. Put this just before </body> in page() (keep the doubled braces {{ }}, because the HTML goes through .format()):
<p>Live: <span id="t">--</span> °C</p>
<script>
async function tick(){{
try {{
const r = await fetch('/api');
const d = await r.json();
document.getElementById('t').textContent = d.temp_c.toFixed(1);
}} catch(e) {{}}
}}
setInterval(tick, 2000); tick();
</script>The same approach works for buttons: make them call fetch('/led/on') instead of navigating, and the page never reloads. For many updates per second a WebSocket is more efficient, but polling every second or two is perfectly fine on a Pico W.
How it works
| Piece | What it does |
|---|---|
asyncio.start_server(handle, "0.0.0.0", 80) | Listens on port 80 of every interface and calls handle for each browser request |
reader.readline() | The first line is the request, e.g. GET /led/on HTTP/1.1; the loop then skips the header lines |
| Path check | /led/on, /led/off, /api decide the action and the reply |
| Response | Status line, headers, a blank line, then the body |
Connection: close | Tells the browser not to keep the connection open, which keeps the tiny server simple |
wlan.config(pm=0xa11140) | Turns off Wi-Fi power saving so the Pico answers promptly |
The internal temperature sensor measures the RP2040 chip, not the room. It reads a few degrees above ambient and is only accurate to a few degrees. For room temperature, add a DHT22, BME280 or DS18B20 and put its reading in page() and /api.
Use an external LED or relay instead
Swap machine.Pin("LED", …) for a GPIO, for example machine.Pin(15, machine.Pin.OUT), with GP15 → 220 Ω → LED → GND. For a relay module use a free GPIO and check whether the module is active-low; for anything mains-powered use a rated, enclosed relay and keep the server on your home network only. Pin details: Pico W pinout.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ImportError: no module named 'network' | Plain Pico firmware on a Pico W | Flash the Pico W MicroPython UF2 |
| Wi-Fi status −2 | SSID not found (5 GHz-only, typo, out of range) | Use 2.4 GHz; check the name's spelling and case |
| Wi-Fi status −3 | Wrong password | Re-type it in secrets.py |
OSError: [Errno 98] EADDRINUSE | Old server still holds port 80 after Stop | Press Ctrl+D (soft reset) or unplug and replug |
| Page loads slowly or times out | Wi-Fi power saving, weak signal | wlan.config(pm=0xa11140); move closer |
| Works on the Pico's IP but not from a phone | Phone on a guest network or mobile data | Same Wi-Fi network as the Pico |
OSError: [Errno 12] ENOMEM | Huge HTML string or many requests at once | Keep pages small; serve images from elsewhere |
| LED doesn't switch | Pin(25) used (plain-Pico LED pin) | Use Pin("LED") on the Pico W |
| Browser shows the page as text | Wrong Content-Type | text/html for pages, application/json for the API |
Security and reliability
- Keep the server on your LAN. There's no password or HTTPS here; don't port-forward it to the internet. Use a VPN for remote access.
- Give the Pico a fixed address with a DHCP reservation in your router, so the URL never changes.
- For unattended use, add a reconnect check: if
wlan.isconnected()is False, callconnect()again from a background task. - Larger projects are easier with the Microdot web framework (installable with
mip), which adds routing and templates.
FAQ
Can I use the same code on an ESP32? Mostly. Change the LED pin, drop the pm setting and the RP2040 temperature lines. ESP32 version: MicroPython ESP32 web server.
Why port 80? It's the default for http://, so you don't need to type a port. Use another port (e.g. 8080) by changing the number and visiting http://<ip>:8080.
Can the Pico W act as its own access point? Yes: network.WLAN(network.AP_IF) with ap.config(ssid="PicoW", password="12345678"), then browse to 192.168.4.1.
Does it work on the Pico 2 W? Yes, with the Pico 2 W MicroPython firmware; the code is identical.
Next steps
- MicroPython on ESP32 and Pico W: complete guide.
- Raspberry Pi Pico W pinout.
- MicroPython MQTT: send readings to Node-RED or Home Assistant instead of a web page.
- MicroPython DHT22: add a real room-temperature sensor.
Official references: Connecting to the internet with Raspberry Pi Pico W and MicroPython asyncio.
Test the server systematically
Before adding more features, verify each layer separately. First confirm that the Pico W joins the intended 2.4 GHz network and prints a usable IP address. From another device on the same LAN, open that address directly. If the page loads, test each route independently: switch the LED on, switch it off, and request /api. Check that the JSON response is valid and that its LED state matches the physical output. Then leave the browser open for several minutes and watch the serial console for exceptions or repeated reconnect messages.
A useful test matrix is:
| Test | Expected result | What a failure suggests |
|---|---|---|
| Open the root page | HTML response | Wi-Fi, IP, server task or request parsing |
| Request /api | Valid JSON | Route handling or response headers |
| Toggle LED | Physical output changes | GPIO selection, polarity or handler |
| Open from a second device | Same page loads | Guest-network isolation or firewall |
| Leave it idle, then retry | Server still responds | Wi-Fi loss or an unhandled exception |
The Pico W's internal temperature reading is a chip-temperature estimate, not an ambient thermometer. Treat it as a demonstration value, and use a separate sensor for room measurements. Likewise, this example is an unauthenticated HTTP server: keep it on a trusted local network, do not expose port 80 through router port forwarding, and do not place Wi-Fi credentials in code that you publish.
Practical limits and next design step
A small MicroPython server is suitable for a few local clients and low-rate status updates. It is not a production web server. Each request consumes memory, the board has limited RAM, and a browser that repeatedly opens connections can compete with sensor and control tasks. Keep responses small, close streams in a finally block, and avoid doing long sensor reads inside a request handler. If the project grows, separate hardware sampling from HTTP handling and let the handler return the latest cached reading. That keeps a slow browser request from delaying the control loop.




