Advertisement
Shamks412

Simple LED control webserver using Raspberry Pi Pico W

Nov 13th, 2022
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | Source Code | 0 0
  1. import network
  2. import socket
  3. import time
  4. import machine
  5.  
  6. from machine import Pin
  7.  
  8. intled = machine.Pin("LED", machine.Pin.OUT)
  9.  
  10. ssid = 'ENTER YOUR SSID'
  11. password = 'ENTER YOUR Wi-Fi PASSWORD'
  12.  
  13. wlan = network.WLAN(network.STA_IF)
  14. wlan.active(True)
  15. wlan.connect(ssid, password)
  16.  
  17. html = """<!DOCTYPE html>
  18.    <html>
  19.        <head> <title>Pico W</title> </head>
  20.        <body> <h1>Pico W</h1>
  21.            <p>Hello World</p>
  22.            <p>
  23.            <a href='/light/on'>Turn Light On</a>
  24.            </p>
  25.            <p>
  26.            <a href='/light/off'>Turn Light Off</a>
  27.            </p>
  28.            <br>
  29.        </body>
  30.    </html>
  31. """
  32.  
  33. # Wait for connect or fail
  34. max_wait = 10
  35. while max_wait > 0:
  36.     if wlan.status() < 0 or wlan.status() >= 3:
  37.         break
  38.     max_wait -= 1
  39.     print('waiting for connection...')
  40.     time.sleep(1)
  41.  
  42. # Handle connection error
  43. if wlan.status() != 3:
  44.     raise RuntimeError('network connection failed')
  45. else:
  46.     print('connected')
  47.     status = wlan.ifconfig()
  48.     print( 'ip = ' + status[0] )
  49.  
  50. # Open socket
  51. addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
  52.  
  53. s = socket.socket()
  54. s.bind(addr)
  55. s.listen(1)
  56.  
  57. print('listening on', addr)
  58.  
  59. stateis = ""
  60.  
  61. # Listen for connections
  62. while True:
  63.     try:
  64.         cl, addr = s.accept()
  65.         print('client connected from', addr)
  66.  
  67.         request = cl.recv(1024)
  68.         print(request)
  69.  
  70.         request = str(request)
  71.         led_on = request.find('/light/on')
  72.         led_off = request.find('/light/off')
  73.         print( 'led on = ' + str(led_on))
  74.         print( 'led off = ' + str(led_off))
  75.  
  76.         if led_on == 6:
  77.             print("led on")
  78.             intled.value(1)
  79.             stateis = "LED is ON"
  80.  
  81.         if led_off == 6:
  82.             print("led off")
  83.             intled.value(0)
  84.             stateis = "LED is OFF"
  85.      
  86.         response = html + stateis
  87.        
  88.         cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
  89.         cl.send(response)
  90.         cl.close()
  91.  
  92.     except OSError as e:
  93.         cl.close()
  94.         print('connection closed')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement