from machine import Pin, PWM
import time
# --- Outputs ---
green_led = Pin(4, Pin.OUT) # Armed status
red_led = Pin(2, Pin.OUT) # Intrusion alert
yellow_led = Pin(5, Pin.OUT) # Vibration alert
buzzer = Pin(15, Pin.OUT) # Buzzer
motor = PWM(Pin(16)) # DC Motor
motor.freq(1000)
# --- Inputs ---
btn1 = Pin(18, Pin.IN, Pin.PULL_DOWN) # Arm system
btn2 = Pin(19, Pin.IN, Pin.PULL_DOWN) # Reset alarm
radar_sensor = Pin(20, Pin.IN, Pin.PULL_DOWN) # Microwave radar
vibration_sensor = Pin(21, Pin.IN, Pin.PULL_DOWN) # Vibration sensor
# --- State ---
system_armed = False
# ─────────────────────────────────────────
# HELPERS
# ─────────────────────────────────────────
def all_off():
green_led.value(0)
red_led.value(0)
yellow_led.value(0)
buzzer.value(0)
motor.duty_u16(0)
def chirp():
"""Single short confirmation beep"""
buzzer.value(1)
time.sleep(0.1)
buzzer.value(0)
# ─────────────────────────────────────────
# PART 1 - ARM SYSTEM
# ─────────────────────────────────────────
def arm_system():
global system_armed
system_armed = True
all_off()
green_led.value(1) # Green LED ON = armed
chirp() # Single confirmation beep
print("System ARMED - Green LED ON")
# ─────────────────────────────────────────
# PART 2 - INTRUSION DETECTED
# ─────────────────────────────────────────
def trigger_intrusion():
print("INTRUSION DETECTED - Red LED + Buzzer ON")
green_led.value(0)
red_led.value(1)
buzzer.value(1)
# Stay ON until BTN2 is pressed
while btn2.value() == 0:
# Vibration always overrides
if vibration_sensor.value() == 1:
trigger_vibration()
return
time.sleep(0.01)
# BTN2 pressed - reset alarm, stay armed
print("Alarm RESET - System still ARMED")
red_led.value(0)
buzzer.value(0)
green_led.value(1)
# ─────────────────────────────────────────
# PART 3 - VIBRATION OVERRIDE
# ─────────────────────────────────────────
def trigger_vibration():
global system_armed
print("VIBRATION DETECTED - Override! Yellow LED + Siren + Motor")
all_off()
motor.duty_u16(65535) # Motor full speed - close window
# Flash yellow LED + siren for 10 seconds
start = time.time()
while time.time() - start < 10:
yellow_led.value(1)
buzzer.value(1)
time.sleep(0.05)
yellow_led.value(0)
buzzer.value(0)
time.sleep(0.05)
all_off()
system_armed = False
print("Vibration response complete - System DISARMED")
# ─────────────────────────────────────────
# MAIN LOOP
# ─────────────────────────────────────────
print("=== Smart Home Security System ===")
print("BTN1 = ARM | BTN2 = RESET ALARM")
while True:
# PART 3: Vibration overrides everything
if vibration_sensor.value() == 1:
trigger_vibration()
# PART 1: Arm system with BTN1
elif btn1.value() == 1:
time.sleep(0.05)
if btn1.value() == 1:
arm_system()
while btn1.value() == 1:
time.sleep(0.01)
# PART 2: Intrusion while armed
elif system_armed and radar_sensor.value() == 1:
trigger_intrusion()
time.sleep(0.05)