#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
const int ROWS = 3;
const int COLS = 3;
const int rowPins[3] = {12, 11, 10};
const int colPins[3] = {4, 3, 2};
int buttonCState[ROWS][COLS] = {};
int buttonPState[ROWS][COLS] = {};
unsigned long lastDebounceTime[ROWS][COLS] = {0};
unsigned long debounceDelay = 150;
void setup() {
Serial.begin(31250);
for (int i = 0; i < ROWS; i++) {
pinMode(rowPins[i], INPUT_PULLUP);
}
for (int j = 0; j < COLS; j++) {
pinMode(colPins[j], OUTPUT);
digitalWrite(colPins[j], HIGH);
}
}
void loop() {
buttons();
}
void buttons() {
for (int col = 0; col < COLS; col++) {
digitalWrite(colPins[col], LOW);
for (int row = 0; row < ROWS; row++) {
buttonCState[row][col] = digitalRead(rowPins[row]);
if ((millis() - lastDebounceTime[row][col]) > debounceDelay) {
if (buttonPState[row][col] != buttonCState[row][col]) {
lastDebounceTime[row][col] = millis();
if (buttonCState[row][col] == LOW) {
MIDI.sendNoteOn(row * COLS + col, 127, 1);
Serial.print("row:");
Serial.print(row);
Serial.print(" col:");
Serial.print(col);
Serial.println(" button on");
} else {
MIDI.sendNoteOff(row * COLS + col, 0, 1);
Serial.print("row:");
Serial.print(row);
Serial.print(" col:");
Serial.print(col);
Serial.println(" button off");
}
buttonPState[row][col] = buttonCState[row][col];
}
}
}
digitalWrite(colPins[col], HIGH);
}
}