serveur-web-led.py

Raspberry Pi Pico 2 W · File : serveur-web-led.py · Language : Python · Use case : Allumer une LED depuis une page web servie par la carte

The board joins the Wi-Fi network and becomes a minimal web server: a page served in raw HTTP shows the LED state and two links to drive it from any device on the local network.

Hardware

A Raspberry Pi Pico 2 W (RP2350 + 2.4 GHz Wi-Fi radio) with MicroPython installed, powered over USB. A 2.4 GHz Wi-Fi network; external LED + 330 Ω resistor.

Wiring

LED on GP15 through 330 Ω to GND. The user LED sits behind the radio chip: use an external LED.

How it works

network.WLAN(sta) associates the board with the access point; socket bind/listen/accept waits for HTTP requests. The requested URL (/on, /off) drives the pin and the HTML reply goes back immediately.

Running it

Install the « Pico 2 W » MicroPython build (BOOTSEL + .uf2), copy the script via Thonny. As on the Pico W, the user LED is not on a GPIO: use an external LED for outputs.

Variants

Add a sensor reading to the page (internal temperature), or serve several pins as /pin/state.

serveur-web-led.py

# Mini serveur web MicroPython : la page affiche l'etat de la LED
# et propose des liens /on et /off. Aucune bibliotheque externe.
import network
import socket
import time
from machine import Pin

WIFI_SSID = "votre-ssid"
WIFI_PASS = "votre-cle"

led = Pin(15, Pin.OUT)   # LED externe sur GP15

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
for _ in range(40):
    if wlan.isconnected():
        break
    time.sleep_ms(500)
print("Adresse IP :", wlan.ifconfig()[0])

serveur = socket.socket()
serveur.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serveur.bind(("0.0.0.0", 80))
serveur.listen(2)
print("Serveur pret sur le port 80")

while True:
    client, adresse = serveur.accept()
    requete = client.recv(200).decode("utf-8", "ignore")
    if "GET /on" in requete:
        led.value(1)
    elif "GET /off" in requete:
        led.value(0)
    etat = "ALLUMEE" if led.value() else "ETEINTE"
    page = ("<h1>LED " + etat + "</h1>"
            "<a href='/on'>Allumer</a> | <a href='/off'>Eteindre</a>")
    reponse = ("HTTP/1.0 200 OK
Content-Type: text/html

" + page)
    client.send(reponse.encode())
    client.close()

← Back to the board