from machine import Pin, ADC, I2C, PWM
import dht
import time
from i2c_lcd import I2cLcd
# =========================
# LCD SETUP
# =========================
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16)
# =========================
# SENSOR SETUP
# =========================
mq2 = ADC(Pin(34))
mq2.atten(ADC.ATTN_11DB)
pir = Pin(32, Pin.IN)
dht_sensor = dht.DHT22(Pin(4))
# =========================
# OUTPUT SETUP
# =========================
green_led = Pin(18, Pin.OUT)
yellow_led = Pin(19, Pin.OUT)
red_led = Pin(23, Pin.OUT)
buzzer = PWM(Pin(5))
buzzer.freq(1000)
# =========================
# STARTUP DISPLAY
# =========================
lcd.clear()
lcd.putstr("SYSTEM START\nInitializing...")
time.sleep(2)
lcd.clear()
lcd.putstr("SYSTEM READY")
time.sleep(1)
# =========================
# MAIN LOOP
# =========================
while True:
try:
# Read sensors
dht_sensor.measure()
temp = dht_sensor.temperature()
gas = mq2.read()
motion = pir.value()
# Reset outputs
green_led.off()
yellow_led.off()
red_led.off()
buzzer.duty(0)
status = "SAFE"
# =========================
# CONDITION LOGIC (SP7)
# =========================
if gas > 2000 and temp > 35:
red_led.on()
buzzer.duty(512)
status = "CRITICAL ALERT"
elif gas > 2000:
red_led.on()
buzzer.duty(512)
status = "GAS ALERT"
elif temp > 35:
red_led.on()
buzzer.duty(512)
status = "FIRE ALERT"
elif motion == 1:
yellow_led.on()
status = "MOTION ALERT"
else:
green_led.on()
status = "SAFE"
# =========================
# LCD DISPLAY (CLEAN UI)
# =========================
lcd.clear()
lcd.putstr("T:{}C G:{}\n".format(temp, gas))
lcd.putstr(status)
# =========================
# SERIAL OUTPUT (IoT SIM)
# =========================
print("Temp:", temp,
"| Gas:", gas,
"| Motion:", motion,
"| Status:", status)
time.sleep(2)
except Exception as e:
print("Error:", e)