import network
import time
import socket
from machine import Pin
# Timeout counter for Wi-Fi connection
timeout = 0
# Initialize Wi-Fi
wifi = network.WLAN(network.STA_IF)
wifi.active(False)
time.sleep(0.5)
wifi.active(True)
wifi.connect('vivo V27','18031992')
if not wifi.isconnected():
print('Connecting...')
while not wifi.isconnected() and timeout < 5:
print(f"Retrying... {5 - timeout}s")
timeout += 1
time.sleep(1)
if wifi.isconnected():
print('Network Config:', wifi.ifconfig())
print('Connected')
else:
print("Failed to connect to Wi-Fi")
raise RuntimeError("Wi-Fi connection failed")
# HTML content
html = '''\
HTTP/1.1 200 OK
Content-Type: text/html
<!DOCTYPE html>
<html>
<center><h2>ESP32 WebServer</h2></center>
<form>
<center>
<h3>LED</h3>
<button name="LED" value="ON" type="submit">ON</button>
<button name="LED" value="OFF" type="submit">OFF</button>
</center>
</form>
</html>
'''
# Setup LED (use GPIO 15 as an example; change if needed)
LED = Pin("LED", Pin.OUT)
LED.value(0)
# Setup socket server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
print("Server is running and waiting for connections...")
while True:
try:
conn, addr = s.accept()
print("Got a connection from", addr)
request = conn.recv(1024).decode('utf-8')
print("Request content:", request)
LED_ON = request.find("/\?LED=ON")
LED_OFF = request.find("/\?LED=OFF")
if LED_ON != -1:
print("Turning LED ON")
LED.value(1)
if LED_OFF != -1:
print("Turning LED OFF")
LED.value(0)
conn.send(html) # Send HTML response
conn.close()
except Exception as e:
print("Error:", e)