import time
import network
import urequests as requests
from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Define the I2C address for the LCD display
I2C_ADDR = 0x27
# Define the total number of rows and columns on the LCD display
totalRows = 2
totalColumns = 16
# Initialize the I2C communication for ESP32
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
# Create an instance of the I2C LCD
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# Display a message on the LCD while connecting
lcd.putstr("Connecting...")
# Connect to Wi-Fi
ssid = 'Wokwi-GUEST'
password = ''
print("Connecting to Wi-Fi...", end="\n")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
# Wait for the Wi-Fi connection to be established
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Connected to Wi-Fi!")
# API keys and URLs for weather and time information
myId = "fea7b349dc6d52fee018704f8f5ffd40"
my_url = f"https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid=c08c4f7c19c790b0a5c2b1229d7ca6a7"
cityNow = "HCM"
api_url = "https://timeapi.io/api/Time/current/zone?timeZone=Asia/Tokyo"
while True:
# Get the current time
response = requests.get(url=api_url).json()
hour = response['hour']
minute = response['minute']
# Display the city name and time on the LCD
lcd.move_to(0, 0)
lcd.putstr(f"{cityNow}, Time: {hour}:{minute}")
if minute % 1 == 0:
# Get current weather information
weather_response = requests.get(url=my_url).json()
print("Current Weather: ", weather_response['weather'][0]["description"])
# Get temperature and humidity
temperature = weather_response['main']['temp']
humidity = weather_response['main']['humidity']
# Display temperature and humidity on the LCD
lcd.move_to(0, 1)
lcd.putstr(f"Temp:{temperature}, Humidity:{humidity} ")
# Wait for 10 seconds before the next iteration
time.sleep(10)