/*
Button box American Truck Simmunlator
Keyboard matrix for 46 buttons
uses 5 pins for the rows 2/3/4/5/6
and 10 pins for the columns 23/25/27/29/31/33/35/39/41
*/
//Keyboard Matrix
int keyrow[] = {23, 25, 27, 29, 31, 33, 35, 37,39,41};
int keycol[] = {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);
}