Raspberry Pi Pico W
Asynchronous Web Server
Using the uasyncio library, you can make your webserver asynchronous. I used the same DS18B20 breakout for this as I did for my sensor circuit. In addition to async code, I added a counter to keep track of the number of page views.

from time import sleep
from network import WLAN, STA_IF
from secrets import secrets
from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
import uasyncio as asyncio
html = """<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Temperature Server</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container-fluid p-5 bg-primary text-white text-center">
<h1>Pico W Temperature Server</h1>
</div>
<div class="container-fluid">
<p>The temperature is %.2f°C.</p>
<p>Page views: %d.</p>
</div>
<body>
</html>
"""
wlan = WLAN(STA_IF)
# set up temperature sensor with onewire
ow = OneWire(Pin(15))
ds = DS18X20(ow)
r = ds.scan()[0]
t = 0
count = 0
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
async def serve_client(reader, writer):
global t, count
request_line = await reader.readline()
print("Request:", request_line)
# skip HTTP header
while await reader.readline() != b'\r\n':
pass
count += 1
response = html % (t, count)
writer.write('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
writer.write(response)
await writer.drain()
await writer.wait_closed()
print("Client disconnected.")
async def main():
global t
print("Connecting to network.")
connect()
print("Setting up server.")
asyncio.create_task(asyncio.start_server(serve_client, "0.0.0.0", 80))
print("Done.")
while True:
ds.convert_temp()
t = round(ds.read_temp(r), 2)
#print(t)
await asyncio.sleep(0.25)
try:
asyncio.run(main())
finally:
asyncio.new_event_loop()
This is the web page shown on a mobile phone connected to the same WiFi network.


