const int ROWS = 4; // Number of rows in the keypad
const int COLS = 4; // Number of columns in the keypad
// Define the connections to rows and columns
int rowPins[ROWS] = {9, 8, 7, 6}; // R1, R2, R3, R4
int colPins[COLS] = {5, 4, 3, 2}; // C1, C2, C3, C4
// Define the key values as per the 4x4 keypad
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
void setup() {
// Set column pins as outputs
for (int i = 0; i < COLS; i++) {
pinMode(colPins[i], OUTPUT);
digitalWrite(colPins[i], HIGH); // Set columns to HIGH (not active)
}
// Set row pins as inputs with pull-up resistors
for (int i = 0; i < ROWS; i++) {
pinMode(rowPins[i], INPUT_PULLUP);
}
Serial.begin(9600); // Start the serial monitor
}
void loop() {
// Scan each column
for (int col = 0; col < COLS; col++) {
// Set the current column LOW (active) and others HIGH (inactive)
digitalWrite(colPins[col], LOW);
// Check each row to see if a key is pressed
for (int row = 0; row < ROWS; row++) {
if (digitalRead(rowPins[row]) == LOW) {
// Print the key corresponding to the row and column
Serial.println(keys[row][col]);
delay(300); // Simple debounce delay to avoid multiple readings
}
}
// Set the current column back to HIGH (inactive)
digitalWrite(colPins[col], HIGH);
}
}