72 lines
1.8 KiB
Python
72 lines
1.8 KiB
Python
import network
|
|
import ntptime
|
|
import time
|
|
from machine import Pin, I2C
|
|
import ssd1306
|
|
|
|
# --- Configuration ---
|
|
try:
|
|
import config as Config
|
|
except ImportError:
|
|
print("ERROR: config.py not found.")
|
|
print("Create config.py on the device with your Wi-Fi and NTP settings.")
|
|
while True:
|
|
time.sleep(2)
|
|
|
|
# --- Hardware Setup ---
|
|
i2c = I2C(0, sda=Pin(16), scl=Pin(17), freq=400000)
|
|
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
|
|
|
|
|
|
def display_message(line1, line2=""):
|
|
oled.fill(0)
|
|
oled.text(line1, 0, 16)
|
|
oled.text(line2, 0, 32)
|
|
oled.show()
|
|
|
|
|
|
# --- Wi-Fi Connection ---
|
|
display_message("Connecting to", "Wi-Fi...")
|
|
wlan = network.WLAN(network.STA_IF)
|
|
wlan.active(True)
|
|
wlan.connect(Config.WIFI_SSID, Config.WIFI_PASSWORD)
|
|
|
|
timeout = 20
|
|
while not wlan.isconnected() and timeout > 0:
|
|
time.sleep(1)
|
|
timeout -= 1
|
|
|
|
if not wlan.isconnected():
|
|
display_message("Wi-Fi Error", "Check settings")
|
|
raise RuntimeError("Failed to connect to Wi-Fi")
|
|
|
|
# --- NTP Synchronization ---
|
|
display_message("Syncing time...", "NTP server")
|
|
try:
|
|
ntptime.settime() # Sets the Pico internal RTC to UTC
|
|
except Exception as e:
|
|
display_message("NTP Failed", str(e))
|
|
time.sleep(3)
|
|
|
|
# Disconnect Wi-Fi to conserve power once time is synchronized
|
|
wlan.active(False)
|
|
|
|
# --- Main Loop ---
|
|
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
|
|
while True:
|
|
# Apply UTC offset to local epoch
|
|
local_epoch = time.time() + (Config.UTC_OFFSET * 3600)
|
|
year, month, day, hour, minute, second, weekday, _ = time.localtime(local_epoch)
|
|
|
|
time_str = f"{hour:02d}:{minute:02d}:{second:02d}"
|
|
date_str = f"{DAYS[weekday]} {year}-{month:02d}-{day:02d}"
|
|
|
|
oled.fill(0)
|
|
# Center-align roughly for 8x8 font
|
|
oled.text(time_str, 32, 20)
|
|
oled.text(date_str, 12, 38)
|
|
oled.show()
|
|
|
|
time.sleep(0.5)
|