#include <Arduino.h>
// ---------------- KEYPAD ----------------
const int ROWS = 5;
const int COLS = 4;
constexpr byte rowPins[ROWS] = {18, 19, 20, 21, 13}; // ATTENTION 13 instead of 14 used here!!!!!!!!!!
constexpr byte colPins[COLS] = {1, 2, 3, 22};
constexpr char EMPTY {' '};
const char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'},
{'E', 'F', 'G', 'H'}
};
char actKey = EMPTY;
// ---------------- SETUP ----------------
void setup() {
Serial.begin(115200);
keyPadSetup();
}
// ---------------- LOOP ----------------
void loop() {
if (KeyPressed()) {
handleKeyPress();
}
}
void keyPadSetup() {
// rows
for (int r = 0; r < ROWS; r++) {
pinMode(rowPins[r], OUTPUT);
digitalWrite(rowPins[r], HIGH);
}
// columns
for (int c = 0; c < COLS; c++) {
pinMode(colPins[c], INPUT_PULLUP);
}
}
bool KeyPressed() {
static char lastKey;
lastKey = actKey;
actKey = EMPTY;
// scan keypad
for (int r = 0; r < ROWS; r++) {
digitalWrite(rowPins[r], LOW);
for (int c = 0; c < COLS; c++) {
if (digitalRead(colPins[c]) == LOW) {
delay(20); // Simple debouncing
if (digitalRead(colPins[c]) == LOW) {
actKey = keys[r][c];
}
}
}
digitalWrite(rowPins[r], HIGH);
}
if (lastKey == actKey){
return false;
}
lastKey = actKey;
return actKey != EMPTY;
}
void handleKeyPress() {
Serial.print("KEY: ");
Serial.println(actKey);
}