How do you scan a matrix keypad?
Short answer: A matrix keypad connects keys at the crossings of rows and columns, so a 4×4 keypad needs 8 pins instead of 16. Configure the columns as inputs with pull-ups and the rows as outputs. Drive one row low at a time, read the columns: a column reading low means the key at that row and column is pressed. Repeat for each row every few milliseconds and debounce the result.
#include <stdint.h>
#define ROWS 4
#define COLS 4
static const char keymap[ROWS][COLS] = {
{'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'},
};
void row_drive(int r, int level); /* board-specific GPIO helpers */
int col_read(int c); /* returns 0 when pressed (pulled up) */
void delay_us(unsigned us);
/* returns the pressed key, or 0 if none; call every 5-10 ms and debounce */
char keypad_scan(void)
{
for (int r = 0; r < ROWS; r++) {
for (int i = 0; i < ROWS; i++) row_drive(i, 1); /* all rows high (inactive) */
row_drive(r, 0); /* select one row */
delay_us(5); /* let the lines settle */
for (int c = 0; c < COLS; c++)
if (col_read(c) == 0)
return keymap[r][c];
}
return 0;
}
Design points to mention
- Settling time: after changing a row, wait a few microseconds before reading; line capacitance and the pull-up resistors make the column take time to change.
- Inactive rows: drive them high or switch them to inputs (high-impedance). Using open-drain outputs avoids short circuits when two keys in the same column are pressed.
- Debouncing: require the same key in two or three consecutive scans.
- Ghosting and masking: pressing three keys at the corners of a rectangle makes a fourth key appear pressed, because current flows through the pressed keys. Diodes in series with each key prevent this (needed for keyboards with n-key rollover).
- Low power: instead of scanning continuously, drive all rows low and enable a pin-change interrupt on the columns; any key press wakes the MCU, which then scans.
Related "classic peripherals" questions: driving a multiplexed seven-segment display uses the same idea in reverse: enable one digit at a time, output its segment pattern, and cycle fast enough (more than 60 Hz per digit) that persistence of vision makes all digits appear lit; the segment current must be higher to keep brightness when each digit is on only 1/N of the time.