from machine import Pin, ADC, time_pulse_us
import time
# --- PIR Sensor ---
pir = Pin(27, Pin.IN)
# --- Ultrasonic Sensor ---
TRIG_PIN = 5
ECHO_PIN = 18
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# --- MQ-2 Gas Sensor (Analog) ---
mq2 = ADC(Pin(34))
mq2.atten(ADC.ATTN_11DB)
mq2.width(ADC.WIDTH_10BIT) # 0–1023
# --- LED + Buzzer Alarm ---
led = Pin(2, Pin.OUT) # Built-in LED (GPIO2)
buzzer = Pin(4, Pin.OUT) # External buzzer on GPIO4
# --- Ultrasonic Distance Function ---
def get_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
duration = time_pulse_us(echo, 1, 30000)
distance = (duration / 2) * 0.0343
return distance
print("Smart Security Alarm System ")
time.sleep(2)
while True:
motion = pir.value() # 1 = motion detected
distance = get_distance() # cm
gas_value = mq2.read() # 0–1023
print("Motion:", motion, " Distance:", distance, "cm Gas:", gas_value)
if motion == 1:
print(" Motion Detected ")
for i in range(3):
led.on(); buzzer.on()
time.sleep(0.2)
led.off(); buzzer.off()
time.sleep(0.2)
if distance < 30:
print(" A person near by door")
for i in range(3):
led.on(); buzzer.on()
time.sleep(0.2)
led.off(); buzzer.off()
time.sleep(0.2)
if gas_value > 600:
print(" Gas/Smoke Detected")
for i in range(3):
led.on(); buzzer.on()
time.sleep(0.2)
led.off(); buzzer.off()
time.sleep(0.2)
if motion == 0 and distance >= 30 and gas_value <= 600:
print("System Normal")
led.off()
buzzer.off()
time.sleep(1)