from machine import Pin, ADC, time_pulse_us
import time
# PIR sensor
pir = Pin(14, Pin.IN)
# Ultrasonic sensor
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
# MQ-2 Gas sensor (Analog input)
mq2 = ADC(Pin(34))
mq2.atten(ADC.ATTN_11DB) # full 0-3.3V range
# LED alarm
led = Pin(2, Pin.OUT)
# Buzzer alarm
buzzer = Pin(4, Pin.OUT)
# Function: get distance from ultrasonic
def get_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
duration = time_pulse_us(echo, 1, 30000) # wait for echo
distance = (duration / 2) / 29.1 if duration > 0 else 999
return distance
# Main loop
while True:
motion = pir.value()
distance = get_distance()
gas_value = mq2.read()
print("PIR:", motion, " Distance:", distance, "cm Gas:", gas_value)
# Flags to track if any condition triggered
alert_triggered = False
# 🚶 Motion Alert
if motion == 1:
print("🚶 Motion Detected")
led.on()
buzzer.on()
time.sleep(0.2)
buzzer.off()
led.off()
alert_triggered = True
# 🚪 Person Near Door Alert
if distance < 30:
print("🚪 Person Near Door (<30 cm)")
led.on()
buzzer.on()
time.sleep(0.5)
buzzer.off()
led.off()
alert_triggered = True
# 🔥 Gas Leak Alert
if gas_value > 2000: # adjust threshold as needed
print("🔥 Gas Leak Detected")
for _ in range(3): # beep 3 times
led.on()
buzzer.on()
time.sleep(0.2)
buzzer.off()
led.off()
time.sleep(0.2)
alert_triggered = True
# ⚠️ Combined DANGER Alert
if motion == 1 and distance < 30 and gas_value > 2000:
print("⚠️ DANGER: Motion + Person + Gas Detected!")
for _ in range(10): # continuous flashing + buzzer
led.on()
buzzer.on()
time.sleep(0.3)
buzzer.off()
led.off()
time.sleep(0.3)
alert_triggered = True
# ✅ System Normal
if not alert_triggered:
print("✅ System Normal")
led.off()
buzzer.off()
time.sleep(1)