from machine import Pin, I2C
import dht
import time
# I2C: SDA GPIO21, SCL GPIO22
i2c = I2C(
0,
sda=Pin(21),
scl=Pin(22),
freq=100000
)
# DHT22
sensor = dht.DHT22(Pin(15))
# LCD I2C 16x2
from i2c_lcd import I2cLcd
lcd = I2cLcd(i2c, 0x27, 2, 16)
# RTC: DS3231 atau DS1307
RTC_ADDR = 0x68
def bcd_to_int(x):
return (x >> 4) * 10 + (x & 0x0F)
def read_rtc():
d = i2c.readfrom_mem(RTC_ADDR, 0, 7)
sec = bcd_to_int(d[0] & 0x7F)
minute = bcd_to_int(d[1] & 0x7F)
# Mode 24 jam
if d[2] & 0x40:
raise ValueError("RTC harus mode 24 jam")
hour = bcd_to_int(d[2] & 0x3F)
day = bcd_to_int(d[4] & 0x3F)
month = bcd_to_int(d[5] & 0x1F)
year = 2000 + bcd_to_int(d[6])
return day, month, year, hour, minute, sec
lcd.clear()
lcd.putstr("MONITOR SUHU")
lcd.move_to(0, 1)
lcd.putstr("Inisialisasi...")
time.sleep(2)
halaman = 0
while True:
try:
sensor.measure()
suhu = sensor.temperature()
rh = sensor.humidity()
hari, bulan, tahun, jam, menit, detik = read_rtc()
tanggal = "{:02d}/{:02d}/{:04d}".format(
hari, bulan, tahun
)
waktu = "{:02d}:{:02d}:{:02d}".format(
jam, menit, detik
)
lcd.clear()
if halaman == 0:
lcd.putstr("T:{:.1f}C H:{:.1f}%".format(
suhu, rh
)[:16])
lcd.move_to(0, 1)
lcd.putstr("SENSOR AKTIF")
else:
lcd.putstr(tanggal[:16])
lcd.move_to(0, 1)
lcd.putstr(waktu)
print("{} {} | Suhu={:.1f} C | RH={:.1f}%".format(
tanggal, waktu, suhu, rh
))
halaman = 1 - halaman
except Exception as e:
print("Error:", e)
lcd.clear()
lcd.putstr("Cek sensor/RTC")
lcd.move_to(0, 1)
lcd.putstr("Koneksi I2C")
time.sleep(2)
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4