Raspberry Pi - Keypad Door Lock

This tutorial instructs you how to create a password door lock system that utilizes Raspberry Pi, keypad and, solenoid lock or electromagnetic lock, and LCD display.

Raspberry Pi Keypad Door Lock

When an user inputs a correct password via keypad, Raspberry Pi deactivates the solenoid lock to unlock the door. The door remains unlocked for a specific time (e.g. 20 seconds) before automatically locking again. The Raspberry Pi code allows for multiple passwords to be used.

To make it easy, the tutorial is divided into multiple steps, from easy to difficult:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Keypad 3x4 and 4x4 Kit
1×Relay
1×Solenoid Lock
1×12V Power Adapter
1×DC Power Jack
1×Jumper Wires
1×(Optional) Electromagnetic Lock
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Keypad, Solenoid Lock, and Electromagnetic Lock

Both the solenoid lock and electromagnetic lock are used to lock/unlock the door. They primarily differ from each other in term of machanical design. Their wiring to Raspberry Pi are similar. The Raspberry Pi code for controlling them are the same.

If you are not familiar with keypad, solenoid lock, and electromagnetic lock (pinout, how it works, how to program ...), the following tutorials can help you learn:

Wiring Diagram

  • Wiring Diagram with Raspberry Pi, keypad and solenoid lock
The wiring diagram between Raspberry Pi and, keypad, solenoid lock

This image is created using Fritzing. Click to enlarge image

  • Wiring Diagram with Raspberry Pi, keypad and electromagnetic lock
The wiring diagram between Raspberry Pi and, keypad, electromagnetic lock

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code - Keypad Door Lock

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file keypad_lock.py and add the following code:
# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-keypad-door-lock import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'] ] # Define GPIO pins for rows, columns, and relay ROW_PINS = [17, 27, 22, 24] COL_PINS = [25, 8, 7] RELAY_PIN = 16 # Adjust this to the actual GPIO pin connected to the relay # Password to unlock PASSWORD = [1, 2, 3, 4] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROW_PINS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COL_PINS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) # Set up relay pin as an output GPIO.setup(RELAY_PIN, GPIO.OUT) GPIO.output(RELAY_PIN, GPIO.LOW) # Initially, keep the relay off def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COL_PINS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROW_PINS): if GPIO.input(row_pin) == GPIO.LOW: key = KEYPAD[row_num][col_num] # Wait for key release while GPIO.input(row_pin) == GPIO.LOW: time.sleep(0.05) GPIO.output(col_pin, GPIO.HIGH) return key def check_password(input_password): return input_password == PASSWORD entered_keys = [] try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") if pressed_key == '*': entered_keys = [] # reset the input password elif pressed_key == '#': if check_password(entered_keys): print("Password correct! Access granted.") GPIO.output(RELAY_PIN, GPIO.HIGH) # Activate the relay time.sleep(20) # Wait for 20 seconds GPIO.output(RELAY_PIN, GPIO.LOW) # Deactivate the relay break else: print("Incorrect password. Try again.") entered_keys = [] # reset the input password else: entered_keys.append(pressed_key) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 keypad_lock.py
  • Type in 1111 and press #.
  • Then type in 1234 and press #.
  • Check out the lock tongue's state for 20 seconds.
  • Check out the result on the Serial Monitor.
PuTTY - Raspberry Pi
Incorrect password. Try again. Password correct! Access granted.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Code Explanation

The valid passwords are pre-defined in the Raspberry Pi code. A string is utilized to store the password inputted by users, referred to as input string. On the keypad, two keys (* and #) are used for special functions: clearing the password and ending the password. The system works in the following way:

  • Apart from the two special keys, if any other key is pressed, it is added to the input string.
  • If * is pressed, the input string is cleared. This can be used to start or restart entering the password.
  • If # is pressed:
    • Raspberry Pi compares the input string to the pre-defined passwords. If it matches one of the pre-defined passwords, Raspberry Pi deactivates the relay to unlock the door.
    • Regardless of whether the password is correct or not, Raspberry Pi clears the input string for the next input.

Raspberry Pi Code - Multiple Keys

# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-keypad-door-lock import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'] ] # Define GPIO pins for rows, columns, and relay ROW_PINS = [17, 27, 22, 24] COL_PINS = [25, 8, 7] RELAY_PIN = 16 # Adjust this to the actual GPIO pin connected to the relay # Passwords to unlock PASSWORDS = [ [1, 2, 3, 4], # 1st password 1234 [5, 6, 7, 8], # 2nd password 5678 [9, 0, 1, 2] # 3rd password 9012 ] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROW_PINS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COL_PINS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) # Set up relay pin as an output GPIO.setup(RELAY_PIN, GPIO.OUT) GPIO.output(RELAY_PIN, GPIO.LOW) # Initially, keep the relay off def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COL_PINS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROW_PINS): if GPIO.input(row_pin) == GPIO.LOW: key = KEYPAD[row_num][col_num] # Wait for key release while GPIO.input(row_pin) == GPIO.LOW: time.sleep(0.05) GPIO.output(col_pin, GPIO.HIGH) return key def check_password(input_password): return input_password in PASSWORDS entered_keys = [] try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") if pressed_key == '*': entered_keys = [] # reset the input password elif pressed_key == '#': if check_password(entered_keys): print("Password correct! Access granted.") GPIO.output(RELAY_PIN, GPIO.HIGH) # Activate the relay time.sleep(20) # Wait for 20 seconds GPIO.output(RELAY_PIN, GPIO.LOW) # Deactivate the relay break else: print("Incorrect password. Try again.") entered_keys = [] # reset the input password else: entered_keys.append(pressed_key) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()

Adding a door sensor to the keypad door lock

In the previously mentioned code, the Raspberry Pi locks the door after a timeout since unlocking. However, in practical applications, a door sensor is usually added to the system. If the Raspberry Pi detects that the door is closed, it locks the door immediately instead of waiting for the timeout.

To avoid overwhelming you, we didn't include the door sensor in the wiring diagram and code. Instead, we're leaving this part up to your creativity. You can check out the Raspberry Pi - Door Sensor and Raspberry Pi - Door Sensor control Relay tutorials for more guidance.

Video Tutorial