The KeyMatrix scanner scans keys that are wired in a row-column matrix. Each key is wired to a single row line and a single column line. Each row and column line goes to a pin. So for instance a 3x4 matrix of 12 keys will have 3 column lines and 4 row lines. We only need 7 pins (3+4) to scan this matrix instead of 12.
Optionally, there is diode attached to each key as well. This prevents false presses when you press several keys at once.
Here is 2x3 matrix with diodes. In this case, the columns are connected to the diode anodes, and the rows are connected to the cathodes. It could be the other way around.
This example is for a 3x4 matrix, such as the Adafruit 3x4 Matrix Keypad (pictured), the Adafruit Membrane 3x4 Keypad, or the 3x4 Phone-style Matrix Keypad. For details about wiring these keypads, see the Matrix Keypad Guide.
# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import keypad
import board
km = keypad.KeyMatrix(
row_pins=(board.A0, board.A1, board.A2, board.A3),
column_pins=(board.D0, board.D1, board.D2),
)
while True:
event = km.events.get()
if event:
print(event)
Here is some output from this program. Remember that the key numbers start from 0, so they probably don't correspond to the labels on the keys themselves.
<Event: key_number 0 pressed> <Event: key_number 0 released> <Event: key_number 1 pressed> <Event: key_number 1 released> <Event: key_number 3 pressed> <Event: key_number 3 released>
Which Way are the Diodes?
The 3x4 keypads above don't have any diodes, so we don't need specify diode orientation. But if you're building a typing or music keyboard, you probably have diodes, and need to specify their orientation. To do this, you set the columns_to_anodes parameter when you construct the KeyMatrix.
If the column lines are connected to the diode anodes and the rows are connected to the cathodes, set columns_to_anodes to True, which is the default. If the reverse is true, set columns_to_anodes to False.
See the Raspberry Pi RP2350 Erratum Workarounds page in this Guide for workarounds that are needed when using keypad.KeyMatrix on an RP2350.
Here's an example of specifying columns_to_anodes when the diode directions match the schematic at the top of this page:
# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import keypad
import board
km = keypad.KeyMatrix(
row_pins=(board.D0, board.D1, board.D2, board.D3),
column_pins=(board.D4, board.D5, board.D6),
columns_to_anodes=True,
)
while True:
event = km.events.get()
if event:
print(event)
Page last edited May 26, 2025
Text editor powered by tinymce.