Introduction
A 4x4 matrix keypad is an input device that consists of 16 buttons arranged in a 4-row by 4-column grid. This experiment demonstrates how to interface the keypad with an Arduino to read button presses and display them on the Serial Monitor.
Components Needed
- Arduino (e.g., Uno, Nano)
- 4x4 Matrix Keypad
- Breadboard and jumper wires
Circuit Setup
Connect the 4x4 keypad to the Arduino as follows:
- Keypad Pin 1 (Row 1) to Arduino pin 2
- Keypad Pin 2 (Row 2) to Arduino pin 3
- Keypad Pin 3 (Row 3) to Arduino pin 4
- Keypad Pin 4 (Row 4) to Arduino pin 5
- Keypad Pin 5 (Column 1) to Arduino pin 6
- Keypad Pin 6 (Column 2) to Arduino pin 7
- Keypad Pin 7 (Column 3) to Arduino pin 8
- Keypad Pin 8 (Column 4) to Arduino pin 9
Code for 4x4 Matrix Keypad
Upload the following code to your Arduino to detect button presses:
// Include the Keypad library
#include
// Define the number of rows and columns in the keypad
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the keymap
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Connect keypad ROW pins to Arduino pins 2, 3, 4, 5
byte rowPins[ROWS] = {2, 3, 4, 5};
// Connect keypad COLUMN pins to Arduino pins 6, 7, 8, 9
byte colPins[COLS] = {6, 7, 8, 9};
// Create the Keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
Serial.begin(9600);
Serial.println("4x4 Keypad Ready. Press a key:");
}
void loop() {
char key = keypad.getKey(); // Read the key pressed
if (key) { // If a key is pressed
Serial.print("Key Pressed: ");
Serial.println(key);
}
}
Explanation
- Keypad Library: Simplifies the interfacing of the keypad with the Arduino.
- Keymap: Defines the characters corresponding to each button.
- Keypad.getKey(): Reads the key pressed and returns its corresponding character.
if (key)
: Ensures a keypress is detected before displaying output.
Troubleshooting
- If no keys are detected, check the wiring between the keypad and the Arduino.
- If incorrect characters are displayed, verify the keymap matches your keypad's layout.
- Ensure the Keypad library is installed in your Arduino IDE. If not, install it via the Library Manager.
Applications of 4x4 Keypad
Matrix keypads are commonly used in:
- Security systems (e.g., password entry)
- Calculator-style input devices
- Custom user interfaces