要增加每天晚上 4 點 (凌晨 4 點) 進行時間校正的功能並避免進入無限校正迴圈,可以加入一個布林值來追蹤是否已經執行過校正,並在當天執行一次後避免再次執行,直到第二天。
在你的程式中,可以這樣修改:
增加一個 sync_done 變數,用來標記當天的校正是否完成。
只在 sync_done == False 並且時間符合條件的情況下執行 sync_time()。
每天凌晨 4 點校正時間後,將 sync_done 設為 True,並在一天過去後將其重置為 False。
以下是修改後的程式碼片段:
python
複製程式碼
sync_done = False # 標記當天的時間校正是否已完成
while True:
now = time.localtime()
current_date = format_date(now)
current_time = format_time(now)
control_backlight() # 每次循環檢查並控制背光
# 在凌晨4:00進行校正,並確保當天只校正一次
if now[3] == 4 and now[4] == 0 and not sync_done:
sync_time()
sync_done = True # 當天校正完成,設為 True
# 每日日期變化時重置校正標誌
if now[3] == 0 and now[4] == 0 and sync_done:
sync_done = False # 第二天開始,重置校正標誌
# 更新日期和Wi-Fi狀態在第0行
if current_date != previous_date or wifi_status != previous_wifi_status:
wifi_indicator = "W=O" if wifi_status else "W=X"
lcd.move_to(totalColumns - 3, 0) # 將光標移至第0行最右邊
lcd.putstr(wifi_indicator) # 顯示Wi-Fi狀態
lcd.move_to(0, 0)
lcd.putstr(current_date + " " * (totalColumns - len(current_date) - 3))
previous_date = current_date
previous_wifi_status = wifi_status
# 更新時間和溫溼度在第1行
if current_time != previous_time:
lcd.move_to(0, 1)
lcd.putstr(current_time + " " * (totalColumns - len(current_time) - 7)) # 清除時間後的空間
# 讀取 DHT11 資料
temp, hum = read_dht11()
if temp is not None and hum is not None:
lcd.putstr("{:2d}C {:2d}%".format(temp, hum)) # 顯示溫度和濕度
else:
lcd.putstr("NaC Na%") # 顯示錯誤訊息
previous_time = current_time
time.sleep(0.5) # 更新頻率為每0.5秒
新增的變數 sync_done 用來確保每天只校正一次。
當時間是凌晨 4 點 0 分時,程式會檢查 sync_done,如果還未校正,則進行校正並將 sync_done 設為 True。
當日期變化時(凌晨 0 點),sync_done 會被重置,為第二天校正做準備。
這樣可以避免進入不斷的校正迴圈,並確保時間每天都能準確校正一次。