import network
import urequests
import machine
import time
import ntptime # Alternative for direct NTP if preferred
# --- Configuration ---
WIFI_SSID = "YOUR_WIFI_SSID"
WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"
TIME_API_URL = "http://worldtimeapi.org/api/ip" # Example API, returns UTC time in JSON
# --- Functions ---
def connect_wifi():
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(wlan.ifconfig())
print("Connected to Wi-Fi:", wlan.ifconfig())
def get_server_time():
"""Fetches the current time from a server."""
try:
response = urequests.get(TIME_API_URL)
if response.status_code == 200:
data = response.json()
# Assuming the API returns time in ISO 8601 format like: "2023-10-27T10:30:00.123456+00:00"
datetime_str = data.get('utc_datetime')
if datetime_str:
# Parse the ISO 8601 string (up to seconds, ignoring milliseconds and timezone)
year = int(datetime_str[:4])
month = int(datetime_str[5:7])
day = int(datetime_str[8:10])
hour = int(datetime_str[11:13])
minute = int(datetime_str[14:16])
second = int(datetime_str[17:19])
return (year, month, day, hour, minute, second)
else:
print("Error: 'utc_datetime' field not found in API response.")
return None
else:
print(f"Error: HTTP request failed with status code {response.status_code}")
return None
except Exception as e:
print(f"Error fetching time from server: {e}")
return None
finally:
if 'response' in locals():
response.close()
def set_rtc_time(datetime_tuple):
"""Sets the RTC clock with the provided datetime tuple."""
rtc = machine.RTC()
# RTC expects a tuple: (year, month, day, weekday, hours, minutes, seconds, subseconds)
# We can set weekday to 0 as it will be recalculated
rtc.datetime((datetime_tuple[0], datetime_tuple[1], datetime_tuple[2], 0,
datetime_tuple[3], datetime_tuple[4], datetime_tuple[5], 0))
print("RTC set to:", rtc.datetime())
# --- Main Script ---
connect_wifi()
# Option 1: Use an HTTP API to get the time
server_time = get_server_time()
if server_time:
set_rtc_time(server_time)
else:
print("Failed to get time from server, RTC not set.")
# Option 2: (Alternative) Use NTP to sync the time (requires internet connectivity)
# try:
# ntptime.settime()
# print("RTC synced using NTP.")
# rtc = machine.RTC()
# print("RTC time after NTP sync:", rtc.datetime())
# except Exception as e:
# print(f"Error syncing time with NTP: {e}")
print("Script finished.")Loading
pi-pico-w
pi-pico-w