from machine import Pin, I2C, PWM, ADC, RTC
import time
import dht
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
import utime
# Inisialisasi sensor dan komponen
dht_sensor = dht.DHT22(Pin(15))
ldr = ADC(Pin(26))
led = Pin(14, Pin.OUT)
buzzer = PWM(Pin(13))
buzzer.duty_u16(0)
button = Pin(12, Pin.IN, Pin.PULL_UP)
# Setup I2C LCD (alamat bisa 0x27 atau 0x3F, tergantung modul)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# Set waktu manual (tahun, bulan, tanggal, hari, jam, menit, detik, subdetik)
rtc = RTC()
rtc.datetime((2025, 4, 20, 0, 14, 0, 0, 0))
lcd.clear()
lcd.putstr("Monitoring Cuaca")
time.sleep(2)
while True:
try:
# Baca sensor
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
light = ldr.read_u16()
# Ambil waktu dari RTC internal
t = utime.localtime()
jam = t[3]
menit = t[4]
# Deteksi kondisi cahaya
if light < 30000 or jam >= 18 or jam < 6:
status_cahaya = "Gelap"
else:
status_cahaya = "Terang"
# Tampilkan data ke LCD
lcd.clear()
lcd.putstr("T:{:.1f}C H:{:.1f}%".format(temp, hum))
time.sleep(2)
lcd.clear()
lcd.putstr("Cahaya:{}\n{:02d}:{:02d}".format(status_cahaya, jam, menit))
# Alarm jika suhu tinggi
if temp > 40:
led.value(1)
buzzer.duty_u16(30000)
buzzer.freq(1000)
else:
led.value(0)
buzzer.duty_u16(0)
# Reset alarm jika tombol ditekan
if button.value() == 0:
print("Tombol ditekan!")
buzzer.duty_u16(0)
led.value(0)
utime.sleep_ms(200) # debounce
time.sleep(3)
except Exception as e:
lcd.clear()
lcd.putstr("Error!")
print("Error:", e)
time.sleep(2)