int8_t rowpins[] = {16, 15, 14};
int8_t colpins[] = {13, 12, 11, 10, 9, 8};
int8_t rotatoryPins[] = {7, 6, 5, 4};
bool btnStatus[6 * 3]; // We have 6(cols) * 3(rows) buttons/switches
int8_t rotatoryStatus[2 * 3]; // We have 2 rotatory buttons in every row (3)
void setup() {
Serial.println(9600);
// put your setup code here, to run once:
for(uint8_t row = 0; row < (sizeof(rowpins) / sizeof(rowpins[0])); row++) {
pinMode(rowpins[row], OUTPUT);
digitalWrite(rowpins[row], HIGH);
}
for(uint8_t col = 0; col < (sizeof(colpins) / sizeof(colpins[0])); col++) {
pinMode(colpins[col], INPUT_PULLUP);
}
for(uint8_t i = 0; i < (sizeof(rotatoryPins) / sizeof(rotatoryPins[0])); i++) {
pinMode(rotatoryPins[i], INPUT_PULLUP);
}
}
void switchUpdate(uint8_t row, uint8_t col, bool status) {
Serial.print("The switch/button at col ");
Serial.print(col);
Serial.print(" and row ");
Serial.print(row);
Serial.print(" was updated to: ");
Serial.println(status);
}
void rotatoryUpdate(uint8_t row, uint8_t col, uint8_t newVal, uint8_t oldVal) {
Serial.print("The rotatory at col ");
Serial.print(col);
Serial.print(" and row ");
Serial.print(row);
Serial.print(" was updated to ");
Serial.print(newVal);
Serial.print(" from ");
Serial.println(oldVal);
}
void checkInput() {
for(uint8_t row = 0; row < (sizeof(rowpins) / sizeof(rowpins[0])); row++) {
digitalWrite(rowpins[row], LOW);
uint8_t partialIndex = row * (sizeof(colpins) / sizeof(colpins[0]));
// Check normal buttons
for(uint8_t col = 0; col < (sizeof(colpins) / sizeof(colpins[0])); col++) {
uint8_t index = partialIndex + col;
bool status = digitalRead(colpins[col]) == LOW ? true : false;
bool old_status = btnStatus[index];
if(status != old_status) {
switchUpdate(row, col, status);
btnStatus[index] = status;
}
}
// Check rotatory encoders
for(uint8_t i = 0; i < (sizeof(rotatoryPins) / sizeof(rotatoryPins[0])); i+=2) {
uint8_t index = partialIndex + (i / 2);
uint8_t status =
(digitalRead(rotatoryPins[i]) == LOW ? 1 : 0) ^
(digitalRead(rotatoryPins[i + 1]) == LOW ? 2 : 0);
bool old_status = rotatoryStatus[index];
if(status != old_status) {
rotatoryUpdate(row, i / 2, status, old_status);
rotatoryStatus[index] = status;
}
}
digitalWrite(rowpins[row], HIGH); // reset this row
}
}
void loop() {
// put your main code here, to run repeatedly:
checkInput();
}