import RPi.GPIO as GPIO
import time
from pad4pi import rpi_gpio
from Adafruit_CharLCD import Adafruit_CharLCD
from pyfingerprint.pyfingerprint import PyFingerprint
# Pin Definitions
RELAY_PIN = 17
BUZZER_PIN = 18
# Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
# Setup LCD
lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2, 0, 1, 2, 3)
lcd.clear()
# Setup Keypad
KEYPAD = [
[1, 2, 3, 'A'],
[4, 5, 6, 'B'],
[7, 8, 9, 'C'],
['*', 0, '#', 'D']
]
ROW_PINS = [12, 16, 20, 21]
COL_PINS = [6, 13, 19, 26]
factory = rpi_gpio.KeypadFactory()
keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)
# Pre-defined correct PIN
CORRECT_PIN = '1234'
# Setup Fingerprint Sensor
try:
fingerprint_sensor = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
if not fingerprint_sensor.verifyPassword():
raise ValueError('The given fingerprint sensor password is wrong!')
except Exception as e:
print('Fingerprint sensor initialization failed!')
print('Exception message: ' + str(e))
exit(1)
# Function to unlock the door
def unlock_door():
GPIO.output(RELAY_PIN, GPIO.HIGH)
time.sleep(5) # Keep the door unlocked for 5 seconds
GPIO.output(RELAY_PIN, GPIO.LOW)
# Function to trigger buzzer alarm
def trigger_alarm():
GPIO.output(BUZZER_PIN, GPIO.HIGH)
time.sleep(5)
GPIO.output(BUZZER_PIN, GPIO.LOW)
# Keypad event handler
def keypad_handler(key):
global input_pin, incorrect_attempts
if key == '#':
if input_pin == CORRECT_PIN:
lcd.clear()
lcd.message('Enter Fingerprint')
if validate_fingerprint():
lcd.clear()
lcd.message('Access Granted')
unlock_door()
incorrect_attempts = 0
else:
lcd.clear()
lcd.message('Access Denied')
incorrect_attempts += 1
check_incorrect_attempts()
else:
lcd.clear()
lcd.message('Invalid PIN')
incorrect_attempts += 1
check_incorrect_attempts()
input_pin = ''
elif key == '*':
input_pin = ''
lcd.clear()
else:
input_pin += str(key)
lcd.message(str(key))
# Fingerprint validation
def validate_fingerprint():
try:
lcd.clear()
lcd.message('Waiting for finger...')
while not fingerprint_sensor.readImage():
pass
fingerprint_sensor.convertImage(0x01)
result = fingerprint_sensor.searchTemplate()
position_number = result[0]
if position_number >= 0:
return True
else:
return False
except Exception as e:
print('Fingerprint validation failed!')
print('Exception message: ' + str(e))
return False
# Check incorrect attempts and trigger alarm if necessary
def check_incorrect_attempts():
if incorrect_attempts >= 3:
trigger_alarm()
incorrect_attempts = 0
# Main program
input_pin = ''
incorrect_attempts = 0
keypad.registerKeyPressHandler(keypad_handler)
try:
lcd.message('Enter PIN:')
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print("Exiting...")
finally:
GPIO.cleanup()
keypad.cleanup()
lcd.clear()