# LED Matrix Clock with Raspberry Pi Pico
from machine import Pin, SPI
import network
import utime
import sys
import ntptime
import max7219
import wlan
if(sys.platform=="esp32"):
led = Pin(2, Pin.OUT)
disp_sck = 18 # default SCK of SPI(1)
disp_mosi = 23 # default MOSI of SPI(1)
disp_miso = 19 # not use
disp_cs = 5
# 初始化 SPI
spi = SPI(1, baudrate=10000000, polarity=1, phase=0, sck=Pin(disp_sck), mosi=Pin(disp_mosi), miso=Pin(disp_miso))
# spi = SPI(1, baudrate=10000000, sck=Pin(4), mosi=Pin(2))
cs = Pin(disp_cs, Pin.OUT)
elif(sys.platform=="rp2"):
led = Pin("LED", Pin.OUT)
disp_sck = 2 # default SCK of SPI(0)
disp_mosi = 3 # default MOSI of SPI(0)
disp_miso = 4 # not use
disp_cs = 5
spi = SPI(0, baudrate=10000000, polarity=1, phase=0, sck=Pin(disp_sck), mosi=Pin(disp_mosi))
# 初始化 SPI
cs = Pin(disp_cs, Pin.OUT)
INTERVAL = 1000 # millisecond
"""
Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
(date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
(70*365+17)*24*60*60 = 2208988800 =>UTC0
28800 = 8*60*60
2208960000 = 2208988800-28800
"""
# Optional UTC+8 offset time (seconds), if not set, UTC0
# Timezone offset (India = UTC +8:00)
UTC_OFFSET = 28800 # 8 * 60 * 60
# Colon draw function
def draw_colon(x):
display.pixel(x, 2, 1)
display.pixel(x, 5, 1)
display.pixel(x+1, 2, 1)
display.pixel(x+1, 5, 1)
def sync_time_with_retry():
try:
print("Syncing with NTP server...")
ntptime.settime()
# 獲取並顯示本地時間 (台灣時區 +8)
# utime.localtime() 取得 UTC 時間,所以要加上 8 小時
timer = utime.localtime(utime.time() + UTC_OFFSET)
print("Time synchronized.")
return timer
except OSError as e:
# print("Error syncing time:", e)
if e.args[0] == 110: # ETIMEDOUT
print("ETIMEDOUT error during time sync. Retrying in 5 seconds...")
utime.sleep(5)
sync_time_with_retry() # Recursive call to retry
else:
print(f"An unexpected error occurred: {e}")
# Start Function
if __name__ == '__main__':
print("Hello, " + sys.platform + "!")
# ========== CONNECT WIFI ==========
wlan.connect_wifi() # Connecting to WiFi Router
utime.sleep_ms(1000)
# ========== NTP TIME SYNC ==========
led.on()
timer = sync_time_with_retry() # Synchronize the time
led.off()
# ========== SPI MAX7219 ==========
display = max7219.Matrix8x8(spi, cs, 8) # 8 matrices
display.brightness(5)
lastTime = utime.ticks_ms()
# ========== MAIN LOOP ==========
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > INTERVAL):
lastTime = currTime
time_now = utime.localtime(utime.time() + UTC_OFFSET)
hh = "{:02d}".format(time_now[3])
mm = "{:02d}".format(time_now[4])
ss = "{:02d}".format(time_now[5])
# SERIAL PRINT
message_str = "TIME: "+ hh + ":" + mm + ":" + ss
print(message_str)
# DISPLAY
display.fill(0)
display.text(hh, 0, 0, 1)
draw_colon(18)
display.text(mm, 22, 0, 1)
draw_colon(40)
display.text(ss, 44, 0, 1)
display.show()
utime.sleep_ms(100)
except KeyboardInterrupt: # 使用者中斷執行(通常是輸入^C)
print("Stop")
break