Keypad door lock
Enter a 4-digit code on a membrane keypad to "unlock": the Keypad library scans the rows and columns.
Input · Intermediate
In a real product: Smart door lock (Smart home): A code on the keypad unlocks the door.
A 4×4 membrane keypad has 16 keys but only 8 wires: 4 rows and 4 columns. Pressing a key connects its row to its column. The board finds which key it is by scanning. This project checks a 4-digit code.
What you'll learn
- How a key matrix works, and why scanning needs only 8 pins for 16 keys
- Using the Keypad library (from the Arduino Library Manager, listed in
libraries.txt) - Building and comparing a
String
How it works
Rows R1–R4 go to pins 9–6 and columns C1–C4 to pins 5–2. The Keypad library drives one row LOW at a time and reads the columns, which have pull-ups. A column that reads LOW tells it which key in that row is down.
keypad.getKey() returns the key's character, or nothing if no key is pressed. Digits are added to entered. # checks the code and * clears it. The right code (1234) lights the built-in LED.
Try this
- Click the keys while it runs: type 1, 2, 3, 4, then #.
- Lock again after 5 seconds, or after three wrong tries in a row.
- Show the stars on an LCD instead of the Serial Monitor.
sketch.ino
// A keypad door lock: type 1234 then # to unlock (the built-in LED lights); * clears.
#include <Keypad.h>
const byte ROWS = 4, 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 CODE = "1234";
String entered = "";
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Serial.println("Enter the code, then # (* clears)");
}
void loop() {
char key = keypad.getKey();
if (!key) return;
if (key == '*') {
entered = "";
Serial.println(" cleared");
} else if (key == '#') {
bool ok = entered == CODE;
Serial.println(ok ? " unlocked!" : " wrong code");
digitalWrite(LED_BUILTIN, ok ? HIGH : LOW);
entered = "";
} else {
entered += key;
Serial.print('*');
}
}