import network
import ntptime
import utime
from machine import Pin, SoftI2C
from i2c_lcd import I2cLcd
# --- SETUP I2C & LCD ---
i2c = SoftI2C(sda=Pin(21), scl=Pin(22), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# --- SETUP WIFI ---
# Menggunakan Wokwi-GUEST seperti pada contoh
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# Offset waktu untuk WIB (UTC+7) = 7 * 60 * 60 = 25200 detik
TIMEZONE_OFFSET_SECONDS = 25200
lcd.clear()
lcd.putstr("Connecting WiFi.")
print("Creating WLAN class...")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
lcd.putstr(".")
print(".", end="")
utime.sleep(0.5)
print("\nConnected! IP:", sta_if.ifconfig()[0])
lcd.clear()
lcd.putstr("WiFi Connected!")
utime.sleep(1)
# --- SINKRONISASI NTP ---
lcd.clear()
lcd.putstr("Syncing NTP...")
try:
ntptime.settime()
lcd.clear()
lcd.putstr("NTP Sync OK!")
print("Sinkronisasi NTP berhasil!")
except Exception as e:
lcd.clear()
lcd.putstr("NTP Failed!")
print("NTP Error:", e)
utime.sleep(1)
# --- TAMPILKAN WAKTU DI LCD ---
lcd.clear()
while True:
# Mengambil detik sejak epoch lalu ditambah offset WIB
current_time = utime.time() + TIMEZONE_OFFSET_SECONDS
# Konversi ke format tahun, bulan, hari, jam, menit, detik
year, month, day, hour, minute, second, _, _ = utime.localtime(current_time)
# Format agar selalu 2 digit (contoh: 09:05:02)
tanggal = "{:02d}/{:02d}/{:04d}".format(day, month, year)
waktu = "{:02d}:{:02d}:{:02d} WIB".format(hour, minute, second)
# Tampilkan ke LCD
lcd.move_to(0, 0)
lcd.putstr("Tgl: " + tanggal)
lcd.move_to(0, 1)
lcd.putstr("Jam: " + waktu + " ") # Spasi di akhir buat numpuk sisa karakter lama
# Print ke terminal sesuai contoh
print('Waktu saat ini:', '{:02d}:{:02d}:{:02d} {:02d}-{:02d}-{:04d}'.format(hour, minute, second, day, month, year))
utime.sleep(1)