from machine import Pin, ADC, I2C
import dht
import ssd1306
import time
# ================== INISIALISASI ==================
print("STARTING SNUGLY GUARD...")
# DHT22
dht22 = dht.DHT22(Pin(15))
# OLED I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# LED RGB
led_r = Pin(4, Pin.OUT)
led_g = Pin(5, Pin.OUT)
led_b = Pin(2, Pin.OUT)
# Button
button = Pin(14, Pin.IN, Pin.PULL_UP)
# Potensiometer (simulasi suara)
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)
white_noise = False
# ================== FUNGSI ==================
def baca_sensor():
try:
time.sleep(1) # penting untuk DHT
dht22.measure()
t = dht22.temperature()
h = dht22.humidity()
print(f"[SENSOR] {t:.1f}C | {h:.1f}%")
return t, h
except Exception as e:
print("[ERROR DHT]", e)
return None, None
def hitung_comfort(t, h):
if t is None:
return "N/A"
skor = (100 - abs(t - 25)*10 + 100 - abs(h - 50)*2) / 2
if skor >= 80:
return "Nyaman"
elif skor >= 50:
return "Cukup"
else:
return "Buruk"
def update_led(status):
if status == "Nyaman":
led_r.value(0)
led_g.value(1)
led_b.value(0)
elif status == "Cukup":
led_r.value(1)
led_g.value(1)
led_b.value(0)
else:
led_r.value(1)
led_g.value(0)
led_b.value(0)
def tampil_oled(t, h, status):
oled.fill(0)
oled.text("Snugly Guard", 0, 0)
if t is not None:
oled.text(f"T:{t:.1f}C", 0, 16)
oled.text(f"H:{h:.1f}%", 0, 28)
oled.text(status, 0, 40)
oled.text("Noise:" + ("ON" if white_noise else "OFF"), 0, 52)
else:
oled.text("Sensor Error", 0, 30)
oled.show()
def cek_suara():
val = pot.read()
if val > 3000:
print(f"[SUARA] Terdeteksi! ({val})")
return True
return False
# ================== MAIN LOOP ==================
print("SYSTEM READY\n")
last_btn = 0
loop = 0
while True:
try:
loop += 1
print(f"\n--- LOOP {loop} ---")
# Sensor
t, h = baca_sensor()
status = hitung_comfort(t, h)
print("[STATUS]", status)
# OLED
tampil_oled(t, h, status)
# LED
update_led(status)
# Suara
if cek_suara():
print("ALERT! BAYI MENANGIS")
for _ in range(3):
led_r.value(1)
led_g.value(0)
led_b.value(0)
time.sleep(0.2)
update_led(status)
time.sleep(0.2)
# Button toggle
now = time.ticks_ms()
if button.value() == 0 and (now - last_btn) > 300:
last_btn = now
print("[BUTTON] Ditekan")
white_noise = not white_noise
print("WAIT 2s...\n")
time.sleep(2)
except Exception as e:
print("[ERROR LOOP]", e)
time.sleep(1)