from machine import Pin, ADC
import time
# --- Pins ---
pir = Pin(14, Pin.IN)
led = Pin(27, Pin.OUT)
trig = Pin(18, Pin.OUT)
echo = Pin(5, Pin.IN)
mq2 = ADC(Pin(36))
mq2.atten(ADC.ATTN_11DB) # For full range 0-3.3V
# --- Functions ---
def distance_cm():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
pulse_time = 0
# Wait for echo HIGH
while echo.value() == 0:
pass
start = time.ticks_us()
while echo.value() == 1:
pass
end = time.ticks_us()
pulse_time = end - start
distance = (pulse_time / 2) / 29.1 # cm
return distance
def air_quality_ok():
val = mq2.read()
# Threshold (adjust after testing)
if val < 3000: # clean air
return True
else:
return False
# --- Main Loop ---
while True:
motion = pir.value()
obj_distance = distance_cm()
air_ok = air_quality_ok()
print("Motion:", motion, "Distance:", obj_distance, "Air OK:", air_ok)
if motion and obj_distance > 10 and air_ok:
led.on()
else:
led.off()
time.sleep(0.5)