/*
Forum: https://forum.arduino.cc/t/codeproblem-arduino-leonardo-als-tastatur/1160391/3
Wokwi: https://wokwi.com/projects/374340407045785601
Matrix-Tastatur für 7 Zeilen x 5 Spalten = 35 Tasten
benötigt je einen Pin pro Zeile und Spalte = 12 Pins
*/
// Tastaturmatrix
int reihe[] = {2, 3, 4, 5, 6, 7, 8};
int spalte[] = {13, 12, 11, 10, 9};
int col_scan;
int last_scan = -1;
constexpr int anzReihen = sizeof(reihe)/sizeof(reihe[0]);
constexpr int anzSpalten = sizeof(spalte)/sizeof(spalte[0]);
void setup()
{
Serial.begin(9600);
for (int i = 0; i < anzReihen; i++)
{
//Initialisierung der Reihen-PINs
pinMode(reihe[i], OUTPUT);
}
for (int i = 0; i < anzSpalten; i++)
{
//Initialisierung der Spalten-PINs
pinMode(spalte[i], INPUT);
digitalWrite(spalte[i], HIGH);
}
}
int Reihe;
int Spalte;
void loop()
{
if (knopfGedrueckt(Reihe, Spalte)) {
Aktion(Reihe, Spalte);
}
}
boolean knopfGedrueckt(int &Reihe, int &Spalte) {
//Suche nach gedrücktem Knopf
static boolean tasteGedrueckt = false;
static unsigned long letzterDruck = 0;
if (tasteGedrueckt && millis()-letzterDruck < 300) { // Diese 300 ms verhindern, dass
// der Tastendruck "prellt" bzw.
// schnell mehrfach hintereinander
// ausgeführt wird
return false;
}
tasteGedrueckt = false;
for (int i = 0; i < anzReihen; i++)
{
if (tasteGedrueckt) break;
for (int j = 0; j < anzReihen;j++){
digitalWrite(reihe[j], HIGH);
}
digitalWrite(reihe[i], LOW);
for (int j = 0; j < anzSpalten; j++)
{
col_scan = digitalRead(spalte[j]);
if (col_scan == LOW)
{
letzterDruck = millis();
tasteGedrueckt = true;
Reihe = i;
Spalte = j;
break;
}
}
}
return tasteGedrueckt;
}
void Aktion(int i, int j)
{
int tasterNr = i*anzSpalten+j+1;
Serial.print("Taster Nr. ");
Serial.print(tasterNr);
Serial.print("\t");
switch (tasterNr){
case 1 : // Hier die Aktion für Taster 1
Serial.println("Aktion für Taster 1");
break;
case 9 : // Hier die Aktion für Taster 9
Serial.println("Aktion für Taster 9");
break;
case 16 : // Hier die Aktion für Taster 16
Serial.println("Aktion für Taster 16");
break;
default: // und hier für alle eventuell nicht abgefangenen Tasternummern
Serial.println("Hier ist noch keine Aktion hinterlegt ....");
break;
}
}