import RPi.GPIO as GPIO
import time
from machine import Pin
import utime
# Keypad setup
R1 = 28
R2 = 26
R3 = 22
R4 = 21
C1 = 20
C2 = 19
C3 = 17
C4 = 16
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(R1, GPIO.OUT)
GPIO.setup(R2, GPIO.OUT)
GPIO.setup(R3, GPIO.OUT)
GPIO.setup(R4, GPIO.OUT)
GPIO.setup(C1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(C2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(C3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(C4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# Define the PIR sensor input and buzzer output pins
pir_pin = Pin(18, Pin.IN)
buzzer_pin = Pin(27, Pin.OUT)
led = Pin(5, Pin.OUT)
# Define the password and a variable to store the entered password
password = "1234"
entered_password = ""
motion_detected_flag = False
# Function to activate the buzzer when motion is detected
def motion_detected(pin):
global motion_detected_flag
print("Motion detected!")
buzzer_pin.on() # Turn on the buzzer
led.on() # Turn on the LED
motion_detected_flag = True
utime.sleep(2) # Keep the buzzer on for 2 seconds
buzzer_pin.off() # Turn off the buzzer
led.off() # Turn off the LED
pir_pin.irq(handler=None) # Disable motion detection until reset
# Configure the PIR sensor to trigger an interrupt on motion
pir_pin.irq(trigger=Pin.IRQ_RISING, handler=motion_detected)
def readLine(line, characters):
global entered_password
GPIO.output(line, GPIO.HIGH)
if GPIO.input(C1) == 1:
print(characters[0])
entered_password += characters[0]
if GPIO.input(C2) == 1:
print(characters[1])
entered_password += characters[1]
if GPIO.input(C3) == 1:
print(characters[2])
entered_password += characters[2]
if GPIO.input(C4) == 1:
print(characters[3])
entered_password += characters[3]
GPIO.output(line, GPIO.LOW)
# Check if the entered password matches the predefined password
if entered_password == password:
print("Password correct. Disabling alarm.")
buzzer_pin.off() # Turn off the buzzer
led.off() # Turn off the LED
entered_password = "" # Reset entered password
pir_pin.irq(trigger=Pin.IRQ_RISING, handler=motion_detected) # Re-enable motion detection
motion_detected_flag = False
elif len(entered_password) >= len(password):
# Reset if password is incorrect or too long
entered_password = ""
try:
while True:
if not motion_detected_flag:
print("Waiting for motion...")
# Call the readLine function for each row of the keypad
readLine(R1, ["1", "2", "3", "A"])
readLine(R2, ["4", "5", "6", "B"])
readLine(R3, ["7", "8", "9", "C"])
readLine(R4, ["*", "0", "#", "D"])
time.sleep(0.1)
except KeyboardInterrupt:
print("\nApplication stopped!")
GPIO.cleanup() # Clean up GPIO pins
pir_pin.irq(handler=None) # Disable the PIR interrupt
buzzer_pin.off() # Turn off the buzzer
led.off()
print("Exiting...")