from machine import Pin
import time
# Initialize the PIR sensor, LED, buzzer, and pushbutton
pir_sensor = Pin(16, Pin.IN) # PIR output pin
led = Pin(17, Pin.OUT) # LED output pin
buzzer = Pin(18, Pin.OUT) # Buzzer output pin
pushbutton = Pin(19, Pin.IN, Pin.PULL_DOWN) # Pushbutton pin with pull-down resistor
# Variables to track alarm state and button press
alarm_state = False
button_last_state = False
button_debounce_time = 0.2 # Debounce delay in seconds
# Function to flash LED and turn on the buzzer
def alarm(intensity=0.2):
led.toggle() # Toggle LED state (on/off)
buzzer.on() # Turn on buzzer
time.sleep(intensity) # LED blink delay
led.toggle() # Toggle LED back (off)
buzzer.off() # Turn off buzzer briefly
time.sleep(intensity) # Pause between flashes
# Main loop to monitor PIR sensor and pushbutton
while True:
# Check if button is pressed (with debouncing)
if pushbutton.value() == 1 and not button_last_state:
alarm_state = False # Stop the alarm
print("Alarm OFF (Button Pressed)")
time.sleep(button_debounce_time) # Debounce delay
button_last_state = True
# Reset button state after release
if pushbutton.value() == 0:
button_last_state = False
# If the alarm is on (motion detected), activate the alarm function
if alarm_state:
alarm() # Call the alarm function to flash the LED and sound the buzzer
# Check if motion is detected
if pir_sensor.value() == 1 and not alarm_state:
alarm_state = True # Start the alarm
print("Motion Detected! Alarm ON")
time.sleep(0.1) # Small delay to avoid excessive checks
Loading
pi-pico-w
pi-pico-w