import network
import socket
from machine import ADC, Pin
# Wi-Fi credentials
SSID = "IQOO Z9 5G"
PASSWORD = "9008512597"
# Connect to Wi-Fi
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print(f"Connecting to Wi-Fi network: {SSID}...")
while not wlan.isconnected():
pass
print("Connected! IP address:", wlan.ifconfig()[0])
return wlan.ifconfig()[0]
# Set up the ADC sensor on GPIO 26
sensor = ADC(Pin(26))
# HTML with JavaScript for real-time data update
html = """
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Sensor Data</title>
<script>
async function fetchData() {
const response = await fetch('/sensor');
const data = await response.text();
document.getElementById('value').textContent = data;
setTimeout(fetchData, 1000);
}
window.onload = fetchData;
</script>
</head>
<body>
<h1>Real-Time Sensor Data</h1>
<p>Sensor Value: <span id="value">Loading...</span></p>
</body>
</html>
"""
# Start the HTTP server
def start_server(ip):
addr = socket.getaddrinfo(ip, 80)[0][-1]
server_socket = socket.socket()
server_socket.bind(addr)
server_socket.listen(1)
print(f"Server running at http://{ip}/")
try:
while True:
conn, addr = server_socket.accept()
print(f"Connection from {addr}")
try:
request = conn.recv(1024).decode()
print("Request received:", request)
if "GET /sensor" in request:
sensor_value = str(sensor.read_u16())
conn.send("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" + sensor_value)
else:
conn.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" + html)
except Exception as e:
print("Error processing request:", e)
finally:
conn.close()
except KeyboardInterrupt:
print("\nServer stopped manually.")
except Exception as e:
print(f"Server encountered an error: {e}")
finally:
server_socket.close()
print("Socket closed.")
# Main program
if __name__ == "__main__":
try:
ip_address = connect_to_wifi()
start_server(ip_address)
except Exception as e:
print(f"Program encountered an error: {e}")