from machine import Pin, PWM, I2C
import time
# Set up PIR sensor pin, LED pins, Buzzer pin, and Servo motor pin
pir = Pin(13, Pin.IN)
green_led = Pin(14, Pin.OUT) # Green LED on GPIO 14
red_led = Pin(15, Pin.OUT) # Red LED on GPIO 15
buzzer = PWM(Pin(12)) # Buzzer on GPIO 12 (PWM for sound control)
servo = PWM(Pin(16)) # Servo motor on GPIO 16 (for door control)
servo.freq(50) # Standard frequency for servos (50Hz)
# LCD Configuration
I2C_ADDR = 0x27
LCD_ROWS = 2
LCD_COLS = 16
# Set up I2C for LCD
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
lcd = I2cLcd(i2c, I2C_ADDR, LCD_ROWS, LCD_COLS)
# Function to set servo angle
def set_servo_angle(angle):
# Map the angle (0-180 degrees) to duty cycle (40-115)
duty = int((angle / 180) * 75) + 40 # Scale angle to servo PWM range
servo.duty(duty)
print(f"Servo set to {angle} degrees")
while True:
if pir.value() == 1: # Motion detected
green_led.on() # Turn on green LED
red_led.off() # Turn off red LED
set_servo_angle(180) # Open door (servo at 180 degrees)
# Activate buzzer continuously
buzzer.freq(1000) # Set frequency to 1000 Hz
buzzer.duty(512) # Set buzzer to a medium volume
# Update LCD
lcd.clear()
lcd.putstr("Motion Detected!")
print("Motion detected! Door opened.")
time.sleep(5) # Keep the system active for 5 seconds
else: # No motion detected
green_led.off() # Turn off green LED
red_led.on() # Turn on red LED
set_servo_angle(0) # Close door (servo at 0 degrees)
# Turn off the buzzer
buzzer.duty(0)
# Update LCD
lcd.clear()
lcd.putstr("No Motion")
print("No motion. Door closed.")
time.sleep(1) # Delay for the next loop iteration