from machine import Pin
from utime import sleep
import network
# Connect to your WiFi network
wifi_ssid = "wokwi-GUEST"
wifi_password = "" # No password needed for the guest network
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(wifi_ssid, wifi_password)
while not wlan.isconnected():
pass
ip_address = wlan.ifconfig()[0]
print("Connected to WiFi. IP address:", ip_address)
# Function to toggle the LED
def toggle_led():
led.value(not led.value())
# Create LED object on Pin 5
led = Pin(5, Pin.OUT)
# Connect to WiFi
connect_to_wifi()
# Create a web server
import usocket as socket
def start_webserver():
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to port 80
s.bind(('', 80))
s.listen(5)
print("Web server started on port 80")
while True:
# Wait for a client to connect
client, addr = s.accept()
print("Client connected from:", addr)
# Read the HTTP request
request = client.recv(1024)
print("Request received:", request)
# Send HTTP response with LED status
client.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
client.send('<h1>MicroPython Web Server</h1>\n')
client.send('<p>LED is currently {}</p>\n'.format("ON" if led.value() else "OFF"))
client.send('<p><a href="/toggle">Toggle LED</a></p>\n')
# Toggle LED if requested
if '/toggle' in request:
toggle_led()
# Close the connection
client.close()
# Main loop
while True:
# Toggle LED every 2 seconds
toggle_led()
sleep(2)