# 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= 2
# Initialize PIR sensor, LED, and Timer
pir_sensor = Pin(pir_pin, Pin.IN)
led = Pin(20, Pin.OUT)
motion_timer = Timer()
buzzer = PWM(Pin(buzzer_pin, Pin.OUT), freq=1000)
# Function to detect motion and turn on the LED
def detect_motion(pin_value):
if pir_sensor.value() == 1:
print("Motion Detected!")
buzzer.duty_u16(100)
led.on()
motion_timer.deinit() # Stop the timer (if running)
motion_timer.init(mode=Timer.ONE_SHOT, period=5000, callback=turn_off_led)
# Function to turn off the LED after 10 seconds
def turn_off_led(timer):
print("No Motion Detected for 5 seconds.")
buzzer.duty_u16(0)
led.off()
# 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