# Motion detection project
from machine import Pin, Timer, PWM
import utime
# Define GPIO pins
pir_pin = 21 # PIR sensor output pin
led_pin = 20 # LED pin
buzzer_pin = 15 # Buzzer pin
period = 5000 # Period of movement ( in ms )
# Initialize PIR sensor, LED, Timer and Buzzer
pir_sensor = Pin(pir_pin, Pin.IN)
led = Pin(led_pin, Pin.OUT)
buzzer = PWM(Pin(buzzer_pin)) #Pin(buzzer_pin, Pin.OUT)
buzzer.freq(500)
motion_timer = Timer()
# Function to detect motion and turn on the LED
def detect_motion(pin_value):
if pir_sensor.value() == 1:
print("Motion Detected!")
led.on()
buzzer.duty_u16(1000)
motion_timer.deinit() # Stop the timer (if running)
motion_timer.init(mode=Timer.ONE_SHOT, period=period, callback=turn_off_led_and_buzzer)
# Function to turn off the LED and Buzzer after 5 seconds
def turn_off_led_and_buzzer(timer):
print("Buzzer shutdown !")
print(f"No Motion Detected for {int(period/1000)} seconds.")
led.off()
buzzer.duty_u16(0)
# Start the timer
motion_timer.init()
# Attach the function interupt request (irq) with PIR sensor output when pin rises or captures movement
pir_sensor.irq(trigger=Pin.IRQ_RISING, handler=detect_motion)
# Infinite loop to keep the program running
while True:
utime.sleep_ms(10) # Small delay for stability