from machine import Pin, ADC, time_pulse_us
import time
# PIR sensor pin
pir = Pin(13, Pin.IN)
# Ultrasonic pins
trigger = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
# MQ-2 sensor ADC pin
mq2_adc = ADC(Pin(34))
mq2_adc.atten(ADC.ATTN_11DB)
mq2_adc.width(ADC.WIDTH_12BIT)
# LED pin
led = Pin(2, Pin.OUT)
def measure_distance():
# Send trigger pulse
trigger.value(0)
time.sleep_us(2)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
try:
pulse_time = time_pulse_us(echo, 1, 30000)
except Exception:
return None
if pulse_time < 0:
return None
distance_cm = (pulse_time / 2) * 0.0343
return distance_cm
def read_gas():
raw = mq2_adc.read()
return raw
def flash_led():
led.value(1)
time.sleep(0.3)
led.value(0)
time.sleep(0.3)
while True:
motion = pir.value()
dist = measure_distance()
gas_raw = read_gas()
print("PIR:", motion, " Distance:", dist, "cm", " Gas:", gas_raw)
if motion == 1 and dist and dist < 30 and gas_raw > 3000:
print("⚠️ ALERT: Motion + Close Object + Gas!")
flash_led() # blink LED each loop
else:
led.value(0) # keep LED off
time.sleep(0.5)