Raspberry Pi Pico W
Making A Basic Web Server
This page sets up a basic web page served from the Pico W.
from time import sleep
from network import WLAN, STA_IF
from secrets import secrets
from socket import socket, getaddrinfo
html = """<!DOCTYPE html>
<html>
<head>
<title>Pico Test</title>
</head>
<body>
<h1>Pico W</h1>
<p>Hello from the Pico W.</p>
</body>
</html>
"""
wlan = WLAN(STA_IF)
def connect():
wlan.active(True)
wlan.config(pm = 0xa11140)
wlan.connect(secrets["ssid"], secrets["password"])
# try to connect or fail
max_wait = 10
while max_wait >0:
if wlan.status() <0 or wlan.status()>=3:
break
max_wait -= 1
print("Waiting for connection...")
sleep(1)
# connection error
if wlan.status() != 3:
return False
else:
status = wlan.ifconfig()
print("Connected to", secrets["ssid"], "on", status[0])
print()
return True
if not connect():
print("Couldn't connect to WiFi.")
else:
print("We're Online.")
print()
addr = getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket()
s.bind(addr)
s.listen()
print("Listening on", addr)
while True:
try:
cl, addr = s.accept()
print("Client connected from", addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = html
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
except OSError as e:
cl.close()
print("Connection closed")
You use the IP address that is printed to connect to the Pico W from another device on the same WiFi network. Make sure that you are on the same network. In a home, that's unlikely to be a problem. In a school, your WiFi and wired networks may not be the quite the same. I used a phone to connect to this page. The basic HTML is rendered quite small on a phone so I zoomed in for this test shot. You can use frameworks for responsive design to do a more phone-friendly job in more advanced projects. This is just to get things working.


