Advertisement
belrey10

9 – Pico Temperature Reader (Wi-Fi Upgrade)

Nov 7th, 2024 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | Source Code | 0 0
  1. import network
  2. import socket
  3. from time import sleep
  4. from picozero import pico_temp_sensor, pico_led
  5. import machine
  6.  
  7. ssid = 'NAME OF YOUR WIFI NETWORK'
  8. password = 'YOUR SECRET PASSWORD'
  9.  
  10.  
  11. def connect():
  12.     #Connect to WLAN
  13.     wlan = network.WLAN(network.STA_IF)
  14.     wlan.active(True)
  15.     wlan.connect(ssid, password)
  16.     while wlan.isconnected() == False:
  17.         print('Waiting for connection...')
  18.         sleep(1)        
  19.     ip = wlan.ifconfig()[0]
  20.     print(f'Connected on {ip}')
  21.     return ip
  22.  
  23.  
  24.  
  25. def open_socket(ip):
  26.     # Open a socket
  27.     address = (ip, 80)
  28.     connection = socket.socket()
  29.     connection.bind(address)
  30.     connection.listen(1)
  31.     return connection
  32.  
  33.  
  34. def webpage(temperature, state):
  35.     #Template HTML
  36.     html = f"""
  37.            <!DOCTYPE html>
  38.            <html>
  39.            <form action="./lighton">
  40.            <input type="submit" value="Light on" />
  41.            </form>
  42.            <form action="./lightoff">
  43.            <input type="submit" value="Light off" />
  44.            </form>
  45.            <p>LED is {state}</p>
  46.            <p>Temperature is {temperature}</p>
  47.            </body>
  48.            </html>
  49.            """
  50.     return str(html)
  51.  
  52.  
  53. def serve(connection):
  54.     #Start a web server
  55.     state = 'OFF'
  56.     pico_led.off()
  57.     temperature = 0
  58.     while True:
  59.         client = connection.accept()[0]
  60.         request = client.recv(1024)
  61.         request = str(request)
  62.         try:
  63.             request = request.split()[1]
  64.         except IndexError:
  65.             pass
  66.         if request == '/lighton?':
  67.             pico_led.on()
  68.             state = 'ON'
  69.         elif request =='/lightoff?':
  70.             pico_led.off()
  71.             state = 'OFF'
  72.         temperature = pico_temp_sensor.temp
  73.         html = webpage(temperature, state)
  74.         client.send(html)
  75.         client.close()
  76.  
  77.  
  78. try:
  79.     ip = connect()
  80.     connection = open_socket(ip)
  81.     serve(connection)
  82. except KeyboardInterrupt:
  83.     machine.reset()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement