import network
import ntptime
from machine import Pin, I2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from utime import localtime, sleep
# Function to connect to Wi-Fi
def connect_to_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Replace with your SSID and password
while not sta_if.isconnected():
print(".", end="")
sleep(0.5)
print(" Connected!")
# Initialize Wi-Fi connection
connect_to_wifi()
# Initialize I2C LCD
i2c = I2C(scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16) # Replace 0x27 with your LCD address if different
# Function to fetch and display current time
def display_current_time():
while True:
try:
ntptime.settime() # Synchronize with NTP server
current_time = localtime() # Get current time tuple (year, month, day, hour, minute, second, weekday, yearday)
# Calculate adjusted hour (adding 3 hours, adjust UTC offset as needed)
current_hour = (current_time[3] + 3) % 24 # Example: Adding 3 hours
# Update only the parts of the LCD that change
lcd.move_to(0, 0)
lcd.putstr("{:02}:{:02}:{:02}".format(current_hour, current_time[4], current_time[5]))
lcd.move_to(0, 1)
lcd.putstr("{:02}/{:02}/{:04}".format(current_time[2], current_time[1], current_time[0]))
sleep(0.3) # Update time every 0.1 seconds (adjust as needed)
except Exception as e:
print("Error fetching time:", e)
sleep(10) # Retry after 10 seconds if there's an error
# Start displaying current time
display_current_time()