import network
import time
import urequests as requests
# LCD
from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Setup LCD
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.putstr("Open weather")
ssid = 'Wokwi-GUEST'
pw = ''
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, pw)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Kết nối ra ngoài internet
# Bước 1: Tạo request dến Openweather
# Bước 2: Lấy response => xử lý JSON
# Bước 3: In ra console
my_api_key = 'xxxxxxxx' # Thay co them API của mình
# Thêm du lieu ve ap suat.
# Neu áp suất -> 1000 -> bật đèn màu đỏ
# Nếu dưới thì đèn tắt.
# Nếu thiết bị đang sử dung mà mất kết nối internet thì làm thế
# nào?
my_city = 'HaNoi'
my_url = f"https://api.openweathermap.org/data/2.5/weather?q={my_city}&appid={my_api_key}&lang=vi&units=metric"
api_time = "https://timeapi.io/api/Time/current/zone?timeZone=Asia/Bangkok"
while True:
# Lấy thời gian hiện tại
lcd.clear()
try:
response = requests.get(url=api_time).json()
hour = response['hour']
minute = response['minute']
# Reset LCD
lcd.move_to(0, 0)
lcd.putstr(f"{my_city}, {hour}:{minute}")
if(minute % 30 == 0):
res = requests.get(url=my_url).json()
print("Thời tiết hiện tại: ", res['weather'][0]["description"])
# Nhiệt độ
temperature = res['main']['temp']
# print("Nhiệt độ:", temperature)
# Độ ẩm
humidity = res['main']['humidity']
print("Độ ẩm:", humidity)
lcd.move_to(0,1)
lcd.putstr(f"T: {temperature}, H: {humidity}")
except Exception as e:
print(type(e), e)
continue
time.sleep(10)