Take a moment to review the completed code provided above. This is the code you will be working with throughout the lesson.
Start by importing the necessary libraries for this project. Add the following lines of code at the beginning of your script in Thonny editor:
import network
import socket
from time import sleep
from picozero import pico_temp_sensor, pico_led
import machine
Replace 'WIFI_SSID' and 'WIFI_PASSWORD' with your WiFi network's SSID and password. Then, add the following code to create a function called 'connect' that connects your Raspberry Pi Pico to the WiFi network:
ssid = 'WIFI_SSID'
password = 'WIFI_PASSWORD'
def connect():
#Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while wlan.isconnected() == False:
print('Waiting for connection...')
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
Add the following code to create a function called 'open_socket' that opens a socket for your Raspberry Pi Pico:
def open_socket(ip):
# Open a socket
address = (ip, 80)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
print(connection)
return connection
Create a function called 'webpage' that generates the HTML code for your web page. This page will have buttons to turn the LED light on and off, and display the current LED state and temperature:
def webpage(temperature, state):
#Template HTML
html = f"""
<!DOCTYPE html>
<html>
<form action="./lighton">
<input type="submit" value="Light on" />
</form>
<form action="./lightoff">
<input type="submit" value="Light off" />
</form>
<p>LED is {state}</p>
<p>Temperature is {temperature}</p>
</body>
</html>
"""
return str(html)