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.
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:
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 favourite e-commerce shopping cart all needed hardware, so that at the end you will be able to evaluate overall costs and decide if continue with the project or remove them from the shopping cart. So, hardware will be only:
- Raspberry PI Zero W (including proper power supply or using a smartphone micro usb charger with at least 3A) or newer Raspberry PI Board
- high speed micro SD card (at least 16 GB, at least class 10)
- a Matrix Keypad
- (optional) dupont wirings
- (optional) breadboard
Check hardware prices with following links:
Please find below my wiring diagram:
Following pictures show some details from my “lab”:
Prepare Operating System
Make your OS updated:
sudo apt update -y && sudo apt upgrade -y
RPI.GPIO should be already installed (otherwise, you can get it installed with the command “sudo apt install python3-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:
The following will describe each code line.
As for every Python script, we start importing the required modules:
import RPi.GPIO as GPIO import sys import time
Next, we 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):
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 the 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 circuit, PINs from 1 to 4 identify columns in reverse order (from right to left). In the same way, PINs from 5 to 8 identify rows in a reverse way from the bottom to top. For this reason, scanning the matrix with the same order of keypad 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 at the main function, which reads keypad input. This function implements a single scan cycle that checks if any button has been pressed.
We already decided that we’ll trigger rows and read columns. Every single row is put to low (the other remaining to high):
def Keypad4x4Read(cols,rows): for r in rows: GPIO.output(r, GPIO.LOW)
The next statement acquires in one line columns states, associating them to a list variable:
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 a short circuit with the row LOW output, returning only a zero to the results list (for example [1,0,1,1]). This will trigger the if statement, which will use the key_map to recover the 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()
To run this script, you have to use following terminal command:
Then you can try it by pressing matrix keypad buttons and reading results from terminal. To stop this script, use “CTRL+C”.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?