Some links in this post may be affiliate links. We may get paid if you buy something or take an action after clicking one of these, but without addictional costs for you compared to direct buying.

Connect Raspberry PI with Matrix Keypad to get User Codes Input

Raspberry pi 4x4 matrix keypad featured image
0
(0)

One of the most common industry input devices, matrix keypad are frequently installed on phones, domestic appliances and also in some low-cost safe boxes.

4x4 matrix keypad

In this tutorial, I’m going to show you how to connect Raspberry PI to a matrix keypad and get user input from python.

Common matrix keypads are made of thin, flexible material. Sometimes this base can also include an adhesive backside so that you can fix this by simply attaching it.

The most common versions have buttons organized in 3 columns x 4 rows or 4 columns x 4 rows. The first model includes all number digits (from 0 to 9) plus “*” and “#”. The 4×4 version usually adds a final column with A, B, C and D letters.

I’m going to refer, in next paragraphs, the 4×4 version.

Their internal circuit is quite elementary, as buttons have below a mere switch that connects a specific row line to a column line. Each button works in a similar way as explained in switch buttons tutorial. Their crossings identify the specific key in a diagram that can be schematized as follows:

4x4 matrix keypad internal circuit

To use this device and get the pressed key, you need to scan iteratively rows (or columns) and check from columns (or rows) the received status.

In this tutorial I’m going to use a a 4×4 matrix keypad with a Raspberry PI Zero W, but following steps can be also used with other Raspberry PI Computer boards.

What We Need

As usual, I suggest adding from now to your favorite e-commerce shopping cart all needed hardware, so that at the end you will be able to evaluate overall costs and decide if continuing with the project or removing them from the shopping cart. So, hardware will be only:

Raspberry PI Zero WH board

Check hardware prices with following links:

Amazon raspberry pi boards box
Amazon raspberry pi Zero W box
Amazon Micro SD box
Amazon Raspberry PI Power Supply box
Amazon matrix keypad box
Amazon Dupont Wiring box
Amazon Breadboard box

Wiring Diagram

Please find below my wiring diagram:

Raspberry pi 4x4 matrix keypad wiring

Following pictures show some details from my “lab”:

Raspberry pi 4x4 matrix keypad GPIO order
Raspberry pi 4x4 matrix keypad PINs order
Raspberry pi 4x4 matrix keypad cabling

Step-by-Step Procedure

Prepare Operating System

Start installing your operating system on Raspberry PI. You can install Raspberry PI OS Lite (for a headless, performing OS) or Raspberry PI OS Desktop (in this case using its internal terminal).

Make your OS updated:

sudo apt update -y && sudo apt upgrade -y

Install RPI.GPIO, as it enables PIN interfacing and management from Python:

sudo apt install rpi.gpio

Prepare 4×4 Matrix Keypad Script for Python

You can get my python script for your Matrix Keypad directly in your Raspberry PI with following command from terminal:

wget https://peppe8o.com/download/python/4x4MatrixKeypad.py

Following will describe each code line.

As for every Python script, we start importing required modules:

import RPi.GPIO as GPIO
import sys
import time

Next, wWe associate PINs mapping to 2 list variables so that we can manage them in a simpler way. The following part uses my wiring settings, according to BCM naming (please refer to Raspberry PI pinout):

col_list=[24,25,8,7]
row_list=[12,16,20,21]

We’ll use rows to scan matrix keypad, so working in output mode (with default to high). On the other hand, column values will be read for intercepting user input, so working in input mode. In next code lines GPIO PINs are set accordingly:

GPIO.setmode(GPIO.BCM)
for pin in row_list:
  GPIO.setup(pin,GPIO.OUT)
  GPIO.output(pin, GPIO.HIGH)

for pin in col_list:
  GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Keypad map will create a resolution list able to use indexes to give back the related key. Comparing to matrix corcuit, PINs from 1 to 4 identify columns in reverse order (from right to left). In same way, PINs from 5 to 8 identify rows in reverse way from bottom to top. For this reason, scanning the matrix with same order of keypan PINs will require a reverse map definition:

key_map=[["D","#","0","*"],\
        ["C","9","8","7"],\
        ["B","6","5","4"],\
        ["A","3","2","1"]]

We now arrive to main function, which reads keypad input. This function implements a single scan cycle which checks if any button has been pressed.

We already decided that we’ll trigger rows and read columns. Each single row is put to low (the other remaining to high):

def Keypad4x4Read(cols,rows):
  for r in rows:
    GPIO.output(r, GPIO.LOW)

Next statement acquire in one line columns states, associating them to a list variable:

result=[GPIO.input(cols[0]),GPIO.input(cols[1]),GPIO.input(cols[2]),GPIO.input(cols[3])]

We defined column PINs to default high (with previous pull_up_down=GPIO.PUD_UP option) when not connected to any source. This will get “result=[1,1,1,1]” when no keys are pressed and min(result) will be “1”. In this case, next if statement isn’t activated and row output is restored to HIGH. This will be repeated for all rows and then the function will exit with a “None” result.

If the user presses any key, its column will be in short circuit with the row LOW output, returning only a zero to results list (for example [1,0,1,1]). This will trigger the if statement, which will use the key_map to recover pressed key value and then exit from function giving back to program the pressed key value:

    if min(result)==0:
      key=key_map[int(rows.index(r))][int(result.index(0))]
      GPIO.output(r, GPIO.HIGH) # manages key keept pressed
      return(key)
    GPIO.output(r, GPIO.HIGH)

The final lines are a simple usage loop, where our script makes an infinite loop calling continuously the keypad function already described. When our function gives us a value different from “None” (this means that user has pressed a key), the result will be printed to the terminal and an additional delay is set to give user enough time to release (and avoid unwanted multiple inputs from a single pressure).

while True:
  try:
    key=Keypad4x4Read(col_list, row_list)
    if key != None:
      print("You pressed: "+key)
      time.sleep(0.3)

As this script runs in an infinite loop, the except statement catches “CTRL+C” interrupt as program termination, cleaning GPIOs status before exiting:

  except KeyboardInterrupt:
    GPIO.cleanup()
    sys.exit()

Script Usage

To run this script, you have to use following terminal command:

python3 4x4MatrixKeypad.py

Then you can try it by presing matrix keypad buttons and reading results from terminal. To stop this script, use “CTRL+C”.

Enjoy!

How useful was this post?

Click on a star to rate it anonymously!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy