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 a simple 2x3 matrix without diodes. There are 2 rows and 3 columns.

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.

Keypad Matrix Example

In this example, a KeypadMatrix is created and then monitored.

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.


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 =
    if 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.

Here's an example of specifying columns_to_anodes when the diode directions match the schematic at the top of this page:

km = keypad.KeyMatrix(
    row_pins=(board.D0, board.D1, board.D2, board.D3),
    column_pins=(board.D4, board.D5, board.D6),

This guide was first published on Jun 29, 2021. It was last updated on Jun 29, 2021.

This page (KeyMatrix) was last updated on Sep 21, 2021.

Text editor powered by tinymce.