#include <Keypad.h>
const int numRows = 3;
const int numCols = 4;
// Define the connections to the button matrix
const int rowPins[numRows] = {2, 3, 4};
const int colPins[numCols] = {5, 6, 7, 8};
// Define the keymap
char keymap[numRows][numCols] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'}
};
void setup() {
Serial.begin(9600);
// Initialize the row pins as outputs
for (int row = 0; row < numRows; row++) {
pinMode(rowPins[row], OUTPUT);
digitalWrite(rowPins[row], HIGH); // Set them to HIGH initially
}
// Initialize the column pins as inputs with pull-up resistors
for (int col = 0; col < numCols; col++) {
pinMode(colPins[col], INPUT_PULLUP);
}
}
void loop() {
for (int row = 0; row < numRows; row++) {
// Set the current row to LOW
digitalWrite(rowPins[row], LOW);
for (int col = 0; col < numCols; col++) {
// Check if the button in the current column is pressed
if (digitalRead(colPins[col]) == LOW) {
char key = keymap[row][col];
Serial.print("Button Pressed: ");
Serial.print(key);
Serial.print(" (Row: ");
Serial.print(row + 1);
Serial.print(", Col: ");
Serial.print(col + 1);
Serial.println(")");
delay(200); // Debounce delay
}
}
// Set the current row back to HIGH
digitalWrite(rowPins[row], HIGH);
}
}