# main.py - serve a page with two buttons that switch the LED.
import network
import socket
import time
from machine import Pin
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
led = Pin("LED", Pin.OUT)
def connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
for _ in range(20):
if wlan.isconnected():
break
time.sleep(1)
if not wlan.isconnected():
raise RuntimeError("wifi failed, status = %d" % wlan.status())
return wlan.ifconfig()[0]
def page(state):
return """HTTP/1.0 200 OK
Content-Type: text/html
<!DOCTYPE html><html><head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pico W</title></head>
<body style="font-family: sans-serif; text-align: center; padding-top: 3rem">
<h1>LED is {state}</h1>
<p><a href="/on">Turn on</a> <a href="/off">Turn off</a></p>
</body></html>
""".format(state=state)
ip = connect()
print("listening on http://%s" % ip)
# addr[0][-1] is the (host, port) tuple getaddrinfo returns for this machine.
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
server = socket.socket()
# Without SO_REUSEADDR, restarting the script gives EADDRINUSE for a minute.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(addr)
server.listen(1)
while True:
client, remote = server.accept()
try:
request = client.recv(1024).decode()
first_line = request.split("\r\n")[0] # e.g. "GET /on HTTP/1.1"
if "/on" in first_line:
led.on()
elif "/off" in first_line:
led.off()
client.send(page("ON" if led.value() else "OFF"))
finally:
# Always close, even on a malformed request - the Pico has a small
# number of sockets and leaking them wedges the server.
client.close()