🛠 Servir une page web depuis la Pico W (socket TCP + HTTP)

Raspberry Pi Pico W · intermediaire · Schéma : IMG-pico-w-intermediaire-1-picow-serveur-web.svg — Pico W connectee au routeur, un navigateur web sur laptop affichant la page servie par l'IP de la carte, fleches de requete HTTP aller-retour, terminal serie affichant la requete recue

Objectives

Once connected to Wi-Fi (connection tutorial), the Pico W is a full network node: it knows how to listen on a TCP port and answer in HTTP. You will write a mini web server with MicroPython's socket module — the same principle as the official picow_httpd example from the pico-examples repository (pico_w/wifi/ folder), in much shorter form. The displayed page can later carry buttons to drive GPIOs: this is the basis of any embedded control interface.

Hardware

Full code

# webserver.py — mini serveur HTTP sur la Pico W (MicroPython)
import machine, network, socket, time

def do_connect:
    wlan = network.WLAN
    wlan.active(True)
    if not wlan.isconnected:
        wlan.connect('my_ssid', 'my_password')
        while not wlan.isconnected:
            machine.idle
    print('IP :', wlan.ipconfig('addr4'))

do_connect

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket
s.bind(addr)
s.listen(1)
print('ecoute sur port 80')
while True:
    cl, remote = s.accept
    req = cl.recv(100)                        # lit la requête HTTP
    print('recu:', req[:40])
    page = (b'HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n'
            b'<h1>Bonjour depuis ma Pico W</h1>'
            b'<p>Rafrichis-moi !</p>')
    cl.write(page)
    cl.close

Expected verification

The serial console displays the IP (e.g. 192.168.1.42). Pointing the browser at http://192.168.1.42/, the page displays and each reload makes the received request scroll in the console. The CYW43439 can also serve as an access point (SoftAP) with up to 4 clients — in this mode, the Pico W itself distributes the network (documented limit of the chip).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials