from machine import Pin
import utime
# Define the PIR sensor input and buzzer output pins
pir_pin = Pin(18, Pin.IN)
buzzer_pin = Pin(27, Pin.OUT)
# Function to activate the buzzer when motion is detected
def motion_detected(pin):
print("Motion detected!")
buzzer_pin.on() # Turn on the buzzer
utime.sleep(2) # Keep the buzzer on for 2 seconds
buzzer_pin.off() # Turn off the buzzer
# Configure the PIR sensor to trigger an interrupt on motion
pir_pin.irq(trigger=Pin.IRQ_RISING, handler=motion_detected)
# Main loop
try:
while True:
print("Waiting for motion...")
utime.sleep(1)
except KeyboardInterrupt:
# Clean up and exit on Ctrl+C
pir_pin.irq(handler=None) # Disable the PIR interrupt
buzzer_pin.off() # Turn off the buzzer
print("Exiting...")