#| ESP32 教學 | MicroPython | RTC 實時時鐘 Real Time Clock
#https://jimirobot.tw/esp32-micropython-rtc-real-time-clock-tutorial-211/
import machine
import time,ntptime,network
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def timeSyn():
#if needed, overwrite default time server
ntptime.host = "time.stdtime.gov.tw"
ntptime.NTP_DELTA = 3155644800
try:
print("Local time before synchronization:%s" %str(time.localtime()))
#make sure to have internet connection
ntptime.settime()
print("Local time after synchronization:%s" %str(time.localtime()))
except:
print("Error syncing time")
timeSyn()
# 定義中文星期的列表
chinese_weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
rtc = machine.RTC()
rtc.init(time.localtime())
while True:
t = rtc.datetime()
# 取得中文星期
chinese_weekday = chinese_weekdays[t[3]]
# 修正這一行,加上格式化字串的 {} 符號,顯示中文星期
print("{:02}-{:02}-{:02} {} {:02}:{:02}:{:02}".format(t[0], t[1], t[2], chinese_weekday, t[4], t[5], t[6]))
time.sleep(60)