/*
Forum: https://forum.arduino.cc/t/codeproblem-arduino-leonardo-als-tastatur/1160391/3
Wokwi: https://wokwi.com/projects/374338338816616449
Keyboard matrix for 72 buttons
uses 6 pins for the rows
and 12 pins for the columns
*/
//Keyboard Matrix
int keyrow[] = {A0, A1, A2, A3, A4, A5};
int keycol[] = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2};
int col_scan;
int last_scan = -1;
constexpr int noOfRows = sizeof(keyrow) / sizeof(keyrow[0]);
constexpr int noOfColumns = sizeof(keycol) / sizeof(keycol[0]);
void setup()
{
Serial.begin(9600);
for (int i = 0; i < noOfRows; i++)
{
//Init rows
pinMode(keyrow[i], OUTPUT);
}
for (int i = 0; i < noOfColumns; i++)
{
//Init columns
pinMode(keycol[i], INPUT);
digitalWrite(keycol[i], HIGH);
}
}
int actRow;
int actCol;
void loop()
{
if (buttonPressed(actRow, actCol)) {
takeAction(actRow, actCol);
}
}
boolean buttonPressed(int &aRow, int &aCol) {
//Suche nach gedrücktem Knopf
static boolean keyPressed = false;
static unsigned long lastPressTime = 0;
if (keyPressed && millis() - lastPressTime < 300) {
// 300 msec as a simple way of debouncing
// and to slow down repetition of the same action
return false;
}
keyPressed = false;
for (int i = 0; i < noOfRows; i++)
{
if (keyPressed) break;
for (int j = 0; j < noOfRows; j++) {
digitalWrite(keyrow[j], HIGH);
}
digitalWrite(keyrow[i], LOW);
for (int j = 0; j < noOfColumns; j++)
{
col_scan = digitalRead(keycol[j]);
if (col_scan == LOW)
{
lastPressTime = millis();
keyPressed = true;
aRow = i;
aCol = j;
break;
}
}
}
return keyPressed;
}
void takeAction(int i, int j)
{
int keyNo = i * noOfColumns + j + 1;
// This is a nice place for switch(keyNo){case 1: ...;} etc.
Serial.print("Key ");
Serial.println(keyNo);
}