from machine import Pin,ADC,PWM
import time
#ultrasonic sensor (HC-SR04)
trigger = Pin(16,Pin.OUT)
echo = Pin(17,Pin.IN)
ldr = ADC(26)
red_led = Pin(14,Pin.OUT)
green_led = Pin(15,Pin.OUT)
buzzer = PWM(Pin(13))
buzzer.freq(1000)
INTRUDER_DISTANCE = 50
DDARK_THRESHOLD = 30000
def measure_distance():
trigger.low()
time.sleep_us(2)
trigger.high()
time.sleep_us(10)
trigger.low()
while echo.value()==0:
start=time.tick_us()
while echo.value()==1:
end =time.tick_us()
duration = time.ticks_diff(end, start)
distance = (duration * 0.0343) / 2
return distance
print("Security System Initialized")
print("----------------------------------")
# ---------------- MAIN LOOP ----------------
while True:
distance = measure_distance()
light_value = ldr.read_u16()
print(f"Distance: {distance:.1f} cm | LDR: {light_value}")
# 🔴 PRIORITY 1: INTRUDER ALERT
if distance < INTRUDER_DISTANCE:
print("🚨 INTRUDER DETECTED!")
red_led.value(1)
green_led.value(0)
buzzer.duty_u16(30000) # Buzzer ON
# 🟢 PRIORITY 2: ENVIRONMENT STATUS
else:
red_led.value(0)
buzzer.duty_u16(0) # Buzzer OFF
if light_value > DARK_THRESHOLD:
print("🌙 Night Watch Mode")
green_led.toggle()
time.sleep(0.5)
else:
print("☀ Day Safe Mode")
green_led.value(1)
time.sleep(0.5)