Lesson 1.5: Matrix keypad
A membrane keypad lets you enter numbers and commands: the code for a lock, a set point or a menu choice.
Parts
Libraries
- Keypad
How it works
The 16 keys form a grid of 4 rows and 4 columns. Pressing a key joins its row to its column, so 8 wires do the job of 16.
To find out which key is pressed the program scans: it activates one row at a time and checks which column responds. The Keypad library does this for you, and debounces the keys too.
getKey() doesn't wait: it returns the key if there's a new press, or a null character if there isn't, so loop() stays free to do other work.
Wiring
| Component | Connects to | Note |
|---|---|---|
| Keypad, wire 1 (row 1) | Pin 9 | Counting from the left, with the keys facing you |
| Keypad, wire 2 (row 2) | Pin 8 | |
| Keypad, wire 3 (row 3) | Pin 7 | |
| Keypad, wire 4 (row 4) | Pin 6 | |
| Keypad, wire 5 (column 1) | Pin 5 | |
| Keypad, wire 6 (column 2) | Pin 4 | |
| Keypad, wire 7 (column 3) | Pin 3 | |
| Keypad, wire 8 (column 4) | Pin 2 |
Code
// Prints each key and checks a four-digit code.
#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const String SECRET = "1234";
String input = "";
void setup() {
Serial.begin(9600);
Serial.println("Type the code and press #");
}
void loop() {
char key = keypad.getKey();
if (!key) return; // no new key
Serial.print(key);
if (key == '#') {
Serial.println(input == SECRET ? " -> correct" : " -> wrong");
input = "";
} else if (key == '*') {
input = "";
Serial.println(" -> cleared");
} else {
input += key;
}
}What the code does
- keys is the map of the grid: what's printed on each key, row by row.
- makeKeymap() turns that matrix into the format the library expects.
- getKey() returns 0 when there's no new press, which is why if (!key) return; leaves loop() without doing anything.
- # confirms the code and * clears it, as on a phone.
Step by step
- Install the «Keypad» library, by Mark Stanley and Alexander Brevig, from the library manager.
- Connect the keypad's eight wires following the table.
- Upload the code and open the serial monitor at 9600 baud.
- Press 1, 2, 3, 4 and #.
Result
Every key shows up on the serial monitor and, when you press #, it says whether the code is correct.
If it doesn't work
- If the wrong keys appear, rows and columns are crossed: reverse the order of rowPins or colPins.
- If a whole row or column doesn't respond, check that wire: the flat connector comes loose easily.