import network
import ntptime
from time import localtime, sleep
import socket
# Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
def connect_wifi():
"""Connect to Wi-Fi."""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
sleep(1)
print(".", end="")
print("\nConnected to Wi-Fi:", wlan.ifconfig())
return wlan
def fetch_ntp_time():
"""Fetch and return the current time from an NTP server."""
try:
ntptime.settime() # Sync Pico's RTC with NTP
current_time = localtime()
return "{:04}-{:02}-{:02} {:02}:{:02}:{:02}".format(
current_time[0], current_time[1], current_time[2],
current_time[3], current_time[4], current_time[5]
)
except Exception as e:
print("Failed to fetch NTP time:", e)
return "NTP Error"
def start_web_server():
"""Start a simple HTTP server to display the time."""
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
server_socket = socket.socket()
server_socket.bind(addr)
server_socket.listen(1)
print("Web server running on http://0.0.0.0:80")
while True:
client, client_addr = server_socket.accept()
print("Client connected from:", client_addr)
request = client.recv(1024)
print("Request:", request)
# Generate HTTP response
time_str = fetch_ntp_time()
response = f"""\
HTTP/1.1 200 OK
<html>
<head><title>Pico W IoT Clock</title></head>
<body>
<h1>Pico W IoT Clock</h1>
<p>Current Time: {time_str}</p>
</body>
</html>
"""
client.send(response)
client.close()
# Main Program
try:
connect_wifi()
start_web_server()
except KeyboardInterrupt:
print("\nProgram terminated.")
wlan.disconnect()