#define ROWS 5
#define COLS 4
#define ENCODER 5
#define DEBOUNCE_DELAY 50
uint8_t rowPins[ROWS] = { 13, 14, 15, 16, 33 };
uint8_t colPins[COLS] = { 17, 18, 19, 21 };
uint8_t keymap[ROWS][COLS] = {
{ 0, 4, 5, 1 },
{ 2, 8, 9, 3 },
{ 6, 12, 13, 7 },
{ 10, 16, 19, 11 },
{ 14, 15, 17, 18 }
};
uint8_t encoderClks[ENCODER] = { 22, 25, 27, 5, 2 };
uint8_t encoderDts[ENCODER] = { 23, 26, 32, 4, 0 };
uint8_t encoderDwn[ENCODER] = { 20, 22, 24, 26, 28 };
uint8_t encoderUpp[ENCODER] = { 21, 23, 25, 27, 29 };
int lastClks[ENCODER] = { HIGH, HIGH, HIGH, HIGH, HIGH };
void setup() {
Serial.begin(115200);
for (uint8_t i = 0; i < ENCODER; i++) {
pinMode(encoderClks[i], INPUT_PULLUP);
pinMode(encoderDts[i], INPUT_PULLUP);
}
for (uint8_t row = 0; row < ROWS; row++) {
pinMode(rowPins[row], OUTPUT);
digitalWrite(rowPins[row], HIGH);
}
for (uint8_t col = 0; col < COLS; col++) {
pinMode(colPins[col], INPUT_PULLUP);
}
Serial.println("Booted!");
}
void loop() {
handleRotaryEncoders();
handleKeypad();
}
void handleRotaryEncoders() {
for (uint8_t i = 0; i < ENCODER; i++) {
int newClk = digitalRead(encoderClks[i]);
if (newClk != lastClks[i]) {
lastClks[i] = newClk;
int dtValue = digitalRead(encoderDts[i]);
if (newClk == LOW && dtValue == HIGH) {
sendKey(encoderUpp[i]);
}
if (newClk == LOW && dtValue == LOW) {
sendKey(encoderDwn[i]);
}
}
}
}
void handleKeypad() {
for (uint8_t row = 0; row < ROWS; row++) {
digitalWrite(rowPins[row], LOW);
for (uint8_t col = 0; col < COLS; col++) {
static bool buttonState[ROWS][COLS] = { false }; // Track button state for debouncing
bool currentState = digitalRead(colPins[col]) == LOW;
if (currentState != buttonState[row][col]) { // State change detected
delay(DEBOUNCE_DELAY); // Wait for debounce delay
currentState = digitalRead(colPins[col]) == LOW; // Read again after delay
if (currentState != buttonState[row][col]) { // If still different, consider it a valid state change
buttonState[row][col] = currentState;
uint8_t key = keymap[row][col];
if (currentState) {
pressKey(key);
} else {
releaseKey(key);
}
}
}
}
digitalWrite(rowPins[row], HIGH);
}
}
void sendKey(uint8_t key) {
uint32_t gamepadbutton = pow(2, key);
Serial.print("pulse\t");
Serial.println(key);
}
void pressKey(uint8_t key) {
uint32_t gamepadbutton = pow(2, key);
Serial.print("hold\t");
Serial.println(key);
}
void releaseKey(uint8_t key) {
uint32_t gamepadbutton = pow(2, key);
Serial.print("release\t");
Serial.println(key);
}