turn_on_led_using_webpage

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
turn_on_led_using_webpage [2026/07/09 18:00] – created walkeradminturn_on_led_using_webpage [2026/07/09 19:07] (current) walkeradmin
Line 6: Line 6:
 ---- ----
 ===== Introduction ===== ===== Introduction =====
 +\\ 
 +I got the idea for this from this webpage [[https://core-electronics.com.au/guides/raspberry-pi-pico-w-create-a-simple-http-server/|here]]. You can also watch a YouTube video about it [[https://www.youtube.com/watch?v=AK8UYh7pMGM|here]]. I decided to add it to my wiki site because (a) so many sites disappear these days and (b) I just wanted to try to add more comments to the code.
 +\\ 
 \\  \\ 
 In this example, we are going to turn on an LED on our Raspberry Pi Pico using a simple web page with two buttons. There is a second function where we can display the state of a hardware button also. In this example, we are going to turn on an LED on our Raspberry Pi Pico using a simple web page with two buttons. There is a second function where we can display the state of a hardware button also.
Line 25: Line 28:
 \\  \\ 
 \\  \\ 
-{{ :corporate:button-led-pico-003.png?500 |}}+{{ :button-led-pico-003.png?500 |}} 
  
 In this example, we have the LED being connected to GP14 (pin 19) and GND (pin 18) via a 100 ohm resistor. You can use one of the GND pins on the Pico, or a common GND rail if you have made one. In this example, we have the LED being connected to GP14 (pin 19) and GND (pin 18) via a 100 ohm resistor. You can use one of the GND pins on the Pico, or a common GND rail if you have made one.
Line 67: Line 71:
 \\  \\ 
 \\  \\ 
-{{ :corporate:button-led-pico-004.mp4?480x360 |}}+{{ :button-led-pico-004.mp4?480x360 |}}
  
 Looking at the simulation above, we can see that when the button is not pressed, we get a delay of 1000mS as per the MicroPython code, so 1 flash every two seconds (1s on, 1s off). Looking at the simulation above, we can see that when the button is not pressed, we get a delay of 1000mS as per the MicroPython code, so 1 flash every two seconds (1s on, 1s off).
Line 240: Line 244:
 \\  \\ 
 \\  \\ 
-{{ :corporate:button-led-pico-005.png?500 |}}+{{ :button-led-pico-005.png?500 |}}
 \\  \\ 
 The page clearly states that the Button is NOT pressed, and the LED is off. The page clearly states that the Button is NOT pressed, and the LED is off.
Line 248: Line 252:
 \\  \\ 
 \\  \\ 
-{{ :corporate:button-led-pico-006.png?500 |}}+{{ :button-led-pico-006.png?500 |}}
 \\  \\ 
 You should see now that the page states that the button IS pressed and that the LED is on. You should see now that the page states that the button IS pressed and that the LED is on.
Line 302: Line 306:
 \\  \\ 
 \\  \\ 
-{{ :corporate:button-led-pico-007.png?800 |}}+{{ :button-led-pico-007.png?800 |}}
 \\  \\ 
 You can now change the LED status on or off by simply clicking the buttons on the webpage, clicking either button also refreshed the webpage. This means, if you hold the button down (or not) and click a button to change the LED, the LED status will change, and the text at the bottom of the webpage will also change to reflect the button status. You can now change the LED status on or off by simply clicking the buttons on the webpage, clicking either button also refreshed the webpage. This means, if you hold the button down (or not) and click a button to change the LED, the LED status will change, and the text at the bottom of the webpage will also change to reflect the button status.
 \\  \\ 
 \\  \\ 
 +----
 +==== Full Code ====
 +
 +<code:python | download>
 +# Simple HTTP Server Example
 +# Control an LED and read a Button using a web browser
 +
 +import time
 +import network
 +import socket
 +from machine import Pin
 +
 +led = Pin(14, Pin.OUT)
 +ledState = 'LED State Unknown'
 +
 +button = Pin(16, Pin.IN, Pin.PULL_UP)
 +
 +ssid = 'YourSSID'
 +password = 'YourWifiPassword'
 +
 +wlan = network.WLAN(network.STA_IF)
 +wlan.active(True)
 +wlan.connect(ssid, password)
 +
 +# replace the "html" variable with the following to create a more user-friendly control panel
 +html = """<!DOCTYPE html><html>
 +<head><meta name="viewport" content="width=device-width, initial-scale=1">
 +<link rel="icon" href="data:,">
 +<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
 +.buttonGreen { background-color: #4CAF50; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }
 +.buttonRed { background-color: #D11D53; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }
 +text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
 +</style></head>
 +<body><center><h1>Control Panel</h1></center><br><br>
 +<form><center>
 +<center> <button class="buttonGreen" name="led" value="on" type="submit">LED ON</button>
 +<br><br>
 +<center> <button class="buttonRed" name="led" value="off" type="submit">LED OFF</button>
 +</form>
 +<br><br>
 +<br><br>
 +<p>%s<p></body></html>
 +"""
 +
 +# Wait for 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...')
 +    time.sleep(1)
 +    
 +# Handle connection error
 +if wlan.status() != 3:
 +    raise RuntimeError('network connection failed')
 +else:
 +    print('Connected')
 +    status = wlan.ifconfig()
 +    print( 'ip = ' + status[0] )
 +    
 +    
 +# Open socket
 +addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
 +s = socket.socket()
 +s.bind(addr)
 +s.listen(1)
 +print('listening on', addr)
 +
 +# Listen for connections, serve client
 +while True:
 +    try:       
 +        cl, addr = s.accept()
 +        print('client connected from', addr)
 +        request = cl.recv(1024)
 +        print("request:")
 +        print(request)
 +        request = str(request)
 +        led_on = request.find('led=on')
 +        led_off = request.find('led=off')
 +        
 +        print( 'led on = ' + str(led_on))
 +        print( 'led off = ' + str(led_off))
 +        
 +        if led_on == 8:
 +            print("led on")
 +            led.value(1)
 +        if led_off == 8:
 +            print("led off")
 +            led.value(0)
 +        
 +        ledState = "LED is OFF" if led.value() == 0 else "LED is ON" # a compact if-else statement
 +        
 +        if button.value() == 1: # button not pressed
 +            print("button NOT pressed")
 +            buttonState = "Button is NOT pressed"
 +        else:
 +            print("button pressed")
 +            buttonState = "Button is pressed"
 +        
 +        # Create and send response
 +        stateis = ledState + " and " + buttonState
 +        response = html % stateis
 +        cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
 +        cl.send(response)
 +        cl.close()
 +        
 +    except OSError as e:
 +        cl.close()
 +        print('connection closed')
 +
 +</code>
 ---- ----
turn_on_led_using_webpage.1783620038.txt.gz · Last modified: by walkeradmin