# Simple HTTP Server Example # Control an LED and read a Button using a web browser import time # Provides sleep and timing functions import network # Wi‑Fi control for Pico W import socket # Low‑level networking (TCP sockets) from machine import Pin # GPIO pin control led = Pin(14, Pin.OUT) # LED on GPIO14 as an output ledState = 'LED State Unknown' # Text placeholder for LED status button = Pin(16, Pin.IN, Pin.PULL_UP) # Button on GPIO16 with pull‑up resistor ssid = 'YourSSID' # Wi‑Fi network name password = 'YourWifiPassword' # Wi‑Fi password wlan = network.WLAN(network.STA_IF) # Use Wi‑Fi in station mode wlan.active(True) # Turn Wi‑Fi hardware on wlan.connect(ssid, password) # Connect to the Wi‑Fi network # HTML template for the webpage html = """ Pico W

Pico W HTTP Server

Hello, World!

%s

""" # Wait for Wi‑Fi connection or timeout max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: # Error or connected break max_wait -= 1 print('waiting for connection...') time.sleep(1) # If not connected, stop the program if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('Connected') status = wlan.ifconfig() # Get IP configuration print('ip = ' + status[0]) # Print IP address # Create a listening TCP socket on port 80 (HTTP) addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] # Bind to all interfaces s = socket.socket() # Create socket s.bind(addr) # Bind to address/port s.listen(1) # Listen for connections print('listening on', addr) # Main server loop while True: try: cl, addr = s.accept() # Accept a client connection print('client connected from', addr) request = cl.recv(1024) # Read HTTP request print("request:") print(request) request = str(request) # Convert bytes → string # Look for URL parameters: ?led=on or ?led=off 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 found at position 8 (typical for GET requests) if led_on == 8: print("led on") led.value(1) if led_off == 8: print("led off") led.value(0) # Update LED state text ledState = "LED is OFF" if led.value() == 0 else "LED is ON" # Read button state if button.value() == 1: # Button not pressed (pull‑up = HIGH) print("button NOT pressed") buttonState = "Button is NOT pressed" led.value(0) # Force LED OFF else: print("button pressed") buttonState = "Button is pressed" led.value(1) # Force LED ON # Build webpage content stateis = ledState + " and " + buttonState response = html % stateis # Insert text into HTML template # Send HTTP response cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() # Close connection except OSError as e: cl.close() print('connection closed')