Getting a keypad to work with circuitpython is fairly straightforward. I followed the code on this website:

https://learn.adafruit.com/matrix-keypad/python-circuitpython

Here were the key take aways from my installation:

  • You have to install the circuit python library “adafruit_matrixkeypad“. I did this through Thonny package manager. The link above tells you to do it through the shell, which is fine too.
  • The input keys need to be digitally mapped to the incoming keys in the code. This is always tricky when setting these things up because each board has their own pin out system. See below for how to do that.

Mapping the pins

In the shell in Thonny I typed in

import board
dir (board)

The output lists all the available pin configurations. I found seven digital pins that were not be used and set that to my pins in this line of code. I then plugged in the pi into those spots.

This means I have a mapping of:



# Membrane 3x4 matrix keypad - https://www.adafruit.com/product/419
cols = [digitalio.DigitalInOut(x) for x in (board.GP18, board.GP17, board.GP16)]
rows = [digitalio.DigitalInOut(x) for x in (board.GP22, board.GP21, board.GP20, board.GP19)]
  • GP16 –> keypad pin 1
  • GP17 –> keypad pin 2
  • GP18 –> keypad pin 3
  • GP19 –> keypad pin 4
  • GP20 –> keypad pin 5
  • GP21 –> keypad pin 6
  • GP22 –> keypad pin 7

So basically I compared that to the code on the website (They use D5, …) and typed in GP16, … in each of the appropriate spots.

Then I ran the code and it worked!

import board
import digitalio
import time
import adafruit_matrixkeypad

# Membrane 3x4 matrix keypad - https://www.adafruit.com/product/419
cols = [digitalio.DigitalInOut(x) for x in (board.GP18, board.GP17, board.GP16)]
rows = [digitalio.DigitalInOut(x) for x in (board.GP22, board.GP21, board.GP20, board.GP19)]

keys = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9),
('*', 0, '#'))

keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys)


while True:
keys = keypad.pressed_keys
if keys:
print("Pressed: ", keys)
time.sleep(0.1)

Output:

>>> %Run -c $EDITOR_CONTENT
Pressed: [1]
Pressed: [1]
Pressed: [1]
Pressed: [1]
Pressed: [9]
Pressed: [9]
Posted in

Leave a Reply


Cosmic Pathways, Lab for Kids, and many of the other research activities discussed on this website is supported by the National Science Foundation and the Physics Teacher Education Coalition (PhysTEC) under grant no. 2325980. Any opinions, findings, and conclusions, or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.