Raspberry Pi - Keypad

This tutorial instructs you how to use Raspberry Pi with keypad 3x4 and 4x4. In detail, we will learn:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Keypad 3x4 and 4x4 Kit
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case for Raspberry Pi 4B

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.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Keypad

Keypad

A keypad is a collection of keys that are organized in rows and columns, referred to as a matrix. Each individual button is known as a key. There are different kinds of keypads. Two of the most commonly used for DIY projects are the 3x4 (12 keys) and 4x4 (16 keys).

The Keypad Pinout

The pins are separated into two categories: rows and columns.

  • A 3x4 keypad has seven pins:. Four of them are row-pins, labeled R1, R2, R3, and R4. The remaining three are column-pins, labeled C1, C2, and C3.
  • A 4x4 keypad has eight pins:. Four of them are row-pins, labeled R1, R2, R3, and R4. The other four are column-pins, labeled C1, C2, C3, and C4.
Keypad pinout

Wiring Diagram

  • The wiring diagram between Raspberry Pi and keypad 3x4
The wiring diagram between Raspberry Pi and Keypad 3x4

This image is created using Fritzing. Click to enlarge image

  • The wiring diagram between Raspberry Pi and keypad 4x4
The wiring diagram between Raspberry Pi and Keypad 3x4

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code

Raspberry Pi Code for Keypad 3x4

""" 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 """ 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 and columns ROWS = [4, 17, 27, 22] COLS = [5, 6, 13] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROWS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COLS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COLS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROWS): 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 try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()

Raspberry Pi Code for Keypad 4x4

""" 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 """ import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3, 'A'], [4, 5, 6, 'B'], [7, 8, 9, 'C'], ['*', 0, '#', 'D'] ] # Define GPIO pins for rows and columns ROWS = [4, 17, 27, 22] COLS = [5, 6, 13, 19] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROWS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COLS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COLS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROWS): 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 try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()

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.py and add one of the above code.
  • Save the file and run the Python script by executing the following command in the terminal:
python3 keypad.py

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

  • Press some keys on the keypad.
  • Check out the result in the Serial Monitor.
PuTTY - Raspberry Pi
3 6 9 4 * #

Keypad and Password

A common use of a keypad is to enter a password. We designate two specific keys for this purpose:

  • A key to initiate or restart the password input, such as the "*" key
  • A key to end the password input, such as the "#" key

The password will comprise of a string that consists of all the other keys, apart from two specific special keys.

When a key is pressed:

  • If the key is not "*" or "#", add the key to the user's input password string.
  • If the key is "#", compare the user's input string with the valid passwords to determine if the input password is correct, then clear the user's input password string.
  • If the key is "*", clear the user's input password string.

Keypad - Password Code

Detailed Instructions

  • Create a Python script file keypad_password.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 """ 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] # 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) 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.") 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_password.py

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

  • Run the code above.
  • Open the Serial Monitor.
  • Press "123456" followed by the "#" key.
  • Press "1234" followed by the "#" key.
  • Check out the result on the Serial Monitor.
PuTTY - Raspberry Pi
Incorrect password. Try again. Password correct! Access granted.

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!