from machine import Pin, PWM
from time import sleep
# Define the GPIO pin for PIR sensor and Servo motor
pir_sensor_pin = 14
servo_pin = 18
# Setup PIR sensor pin
pir_sensor = Pin(pir_sensor_pin, Pin.IN)
# Setup Servo motor pin and configure PWM
servo = PWM(Pin(servo_pin), freq=50)
# Function to move servo motor to a specific angle
def set_servo_angle(angle):
duty = int(40 + (angle / 180) * 75) # Calculate duty cycle for the angle
servo.duty(duty)
# Function to open the door
def open_door():
print("Opening door")
set_servo_angle(90) # Move servo to 90 degrees
sleep(5) # Keep the door open for 5 seconds
close_door()
# Function to close the door
def close_door():
print("Closing door")
set_servo_angle(0) # Move servo to 0 degrees
# Main loop
try:
while True:
if pir_sensor.value() == 1: # Motion detected
print("Motion detected!")
open_door()
sleep(5) # Wait for 5 seconds before checking for motion again
else:
print("No motion")
sleep(1)
except KeyboardInterrupt:
print("Program stopped")
finally:
servo.deinit() # Deinitialize the servo to release the GPIO pin