Raspberry Pi - Keypad - Relay

This tutorial instructs you how to combine a keypad, relay, and Raspberry Pi. If the user enters the correct password on the keypad, the Raspberry Pi will turn on the relay.

The tutorial also provides the Raspberry Pi code which activates a relay over a certain period of time and then deactivates it. Moreover, the Raspberry Pi code is capable of handling multiple passwords.

By connecting a relay to an Electromagnetic Lock, Solenoid Lock, Linear Actuator, Heating Element, Pump, or Fan... We can then control them using a keypad.

Raspberry Pi keypad relay

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Keypad
1×Relay
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
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 and Relay

If you are unfamiliar with keypad and relay (including pinout, functionality, programming, etc.), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and keypad relay

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code - turn relay on if the password is correct

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_relay.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-relay 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 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_relay.py
  • Enter 9765 followed by the # key, then 1234 followed by the # key.
  • Check the Terminal for the result and the state of the relay.
PuTTY - Raspberry Pi
The incorrect password! try again The correct password! Turning ON relay

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

Code Explanation

Authorized passwords are pre-defined in the Raspberry Pi code. A string is used to store the password inputted by users, called input string. In keypad, two keys (* and #) are used for special purposes: clear password and terminate password. When a key on keypad is pressed:

  • If the pressed key is not two special keys, it is appended to the input string.
  • If the pressed key is *, the input string is cleared. This can be used to start or re-start inputing the password.
  • If the pressed key is #:
    • The Raspberry Pi verifies if input string match one of the pre-defined passwords, the relay is turned on.
    • Regardless of whether the password is correct or not, the input string is cleared for the next input.

Raspberry Pi Code - turn a relay on in a period of time if the password is correct

If the password is correct, the relay will be turned on for 5 seconds. After that period of time, it will be switched off.

# 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-relay 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(5) # Wait for 5 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()

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!