Skip to content

Tutorial

Raspberry Pi Pico W Web Server with MicroPython: Control an LED from a Browser

Serve a web page from a Raspberry Pi Pico W with MicroPython: connect to Wi-Fi, switch the onboard LED from a browser, show the chip temperature, add a JSON API.

  • 9 min read
  • Updated November 14, 2026
Raspberry Pi Pico W Web Server with MicroPython: Control an LED from a Browser

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 needNotes
Raspberry Pi Pico W or Pico 2 WThe plain Pico has no Wi-Fi
MicroPython firmware for the Pico WInstall MicroPython on the Pico W
Thonny (or VS Code + mpremote)To edit and run files on the board
2.4 GHz Wi-FiThe Pico W's radio doesn't support 5 GHz
Optional: LED + 220 Ω resistor on GP15Any 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:

main.py
# secrets.py
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
main.py
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 wlan

Status 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.

main.py
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} &deg;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()):

index.html
<p>Live: <span id="t">--</span> &deg;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

PieceWhat 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
ResponseStatus line, headers, a blank line, then the body
Connection: closeTells 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

SymptomLikely causeFix
ImportError: no module named 'network'Plain Pico firmware on a Pico WFlash the Pico W MicroPython UF2
Wi-Fi status −2SSID not found (5 GHz-only, typo, out of range)Use 2.4 GHz; check the name's spelling and case
Wi-Fi status −3Wrong passwordRe-type it in secrets.py
OSError: [Errno 98] EADDRINUSEOld server still holds port 80 after StopPress Ctrl+D (soft reset) or unplug and replug
Page loads slowly or times outWi-Fi power saving, weak signalwlan.config(pm=0xa11140); move closer
Works on the Pico's IP but not from a phonePhone on a guest network or mobile dataSame Wi-Fi network as the Pico
OSError: [Errno 12] ENOMEMHuge HTML string or many requests at onceKeep pages small; serve images from elsewhere
LED doesn't switchPin(25) used (plain-Pico LED pin)Use Pin("LED") on the Pico W
Browser shows the page as textWrong Content-Typetext/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, call connect() 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

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:

TestExpected resultWhat a failure suggests
Open the root pageHTML responseWi-Fi, IP, server task or request parsing
Request /apiValid JSONRoute handling or response headers
Toggle LEDPhysical output changesGPIO selection, polarity or handler
Open from a second deviceSame page loadsGuest-network isolation or firewall
Leave it idle, then retryServer still respondsWi-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.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.