from machine import Pin, I2C
import ssd1306
import urequests
import network
import time
import ntptime
import machine
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 連接到 WiFi
print("Connecting to WiFi...", end="")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "") # 請替換為你的 SSID 和密碼
while not wifi.isconnected():
time.sleep(0.5)
print(".", end="")
print("\nWiFi connected! IP:", wifi.ifconfig()) # 顯示 IP 位址
oled.fill(0)
oled.text('WiFi connected', 0, 0) # 在 OLED 顯示 "WiFi connected"
oled.show()
time.sleep(1)
# 同步網路時間 (使用 NTP)
def sync_time():
try:
ntptime.NTP_DELTA = 3155644800 # 設置台灣的時區 UTC+8
ntptime.host = 'clock.stdtime.gov.tw' # 使用台灣的 NTP 伺服器
ntptime.settime() # 設定時間
print("NTP sync successful")
oled.text('NTP sync OK', 0, 10) # 在 OLED 顯示 "NTP sync OK"
oled.show()
time.sleep(1)
except Exception as e:
print("NTP sync failed:", e)
oled.text('NTP sync Failed', 0, 10) # 顯示 "NTP sync Failed"
oled.show()
time.sleep(1)
sync_time() # 執行時間同步
# 從 OpenWeather API 獲取天氣數據
def get_weather(city, country, api_key):
try:
# 發送 API 請求並獲取返回的 JSON 數據
url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{country}&appid={api_key}&units=metric&lang=zh_tw"
response = urequests.get(url)
data = response.json() # 解析回傳的 JSON
print("API Response:", data) # 打印 API 返回的數據,檢查有無錯誤
if response.status_code == 200: # 檢查是否成功
temp = data["main"]["temp"] # 取得溫度
humidity = data["main"]["humidity"] # 取得濕度
response.close() # 關閉響應
return temp, humidity # 返回溫度和濕度
else:
print(f"Error {response.status_code}: {data}") # 顯示錯誤代碼及訊息
return None, None # 若API請求出錯,返回 None
except Exception as e:
print("Weather API error:", e)
return None, None # 若有錯誤,返回 None
# 你的 OpenWeather API 金鑰(請替換為你自己的金鑰)
api_key = "ff92c2622db85bae90db6291aa3b215e" # 請替換為你的 OpenWeather API 金鑰
# 國家與城市資料(包含台灣、日本、中國、韓國和英國)
cities = [
{"city": "Taipei", "country": "TW"}, # 台灣 台北
{"city": "Tokyo", "country": "JP"}, # 日本 東京
{"city": "Beijing", "country": "CN"}, # 中國 北京
{"city": "Seoul", "country": "KR"}, # 韓國 首爾
{"city": "London", "country": "GB"}, # 英國 倫敦
]
# 主循環
while True:
for location in cities:
city = location["city"]
country = location["country"]
# 獲取天氣數據
temp, humidity = get_weather(city, country, api_key)
# 獲取當前日期和時間
rtc = machine.RTC() # 初始化實時時鐘
t = rtc.datetime() # 獲取當前時間
year, month, day, weekday, hour, minute, second, _ = t # 解構時間元組
weekday_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] # 星期的英文名稱
formatted_time = "{:04}-{:02}-{:02} {} {:02}:{:02}:{:02}".format(
year, month, day, weekday_names[weekday], hour, minute, second
) # 格式化時間字串
# 在 OLED 上顯示天氣數據
oled.fill(0) # 清空顯示屏
oled.text(city, 0, 0) # 顯示城市名稱
oled.text(formatted_time, 0, 10) # 顯示當前時間
if temp is not None:
oled.text(f"Temp: {temp}C", 0, 20) # 顯示溫度
else:
oled.text("Temp: N/A", 0, 20) # 若無法獲取溫度,顯示 "N/A"
if humidity is not None:
oled.text(f"Humidity: {humidity}%", 0, 30) # 顯示濕度
else:
oled.text("Humidity: N/A", 0, 30) # 若無法獲取濕度,顯示 "N/A"
oled.show() # 更新顯示器
# 等待並切換到下一個城市
time.sleep(3) # 每3秒切換一次