/*
Forum:
Wokwi: https://wokwi.com/projects/450406372733697025
Midi notes: C0 = 24, C0# = 25, ... , C5 = 84
*/
constexpr int LOWESTNOTE {24}; // C0 = 24
constexpr char noteNames[] = "C C#D D#E F F#G G#A A#B ";
//Keyboard Matrix
int keycol[] = {7, 6, 5, 4, 3, 2 };
int keyrow[] = {53, 51}; //, 49, 47, 45, 43, 41, 39, 37, 35, 33};
int col_scan;
int last_scan = -1;
constexpr int noOfRows = sizeof(keyrow) / sizeof(keyrow[0]);
constexpr int noOfColumns = sizeof(keycol) / sizeof(keycol[0]);
constexpr int noOfKeys = noOfRows * noOfColumns;
boolean keyMatrix[noOfKeys];
void setup()
{
Serial.begin(115200);
for (int i = 0; i < noOfRows; i++){
digitalWrite(keyrow[i], HIGH);
pinMode(keyrow[i], OUTPUT);
}
for (int i = 0; i < noOfColumns; i++){
pinMode(keycol[i], INPUT_PULLUP);
}
}
void loop()
{
checkKeys();
}
void checkKeys() {
for (int i = 0; i < noOfRows; i++){
digitalWrite(keyrow[i], LOW);
for (int j = 0; j < noOfColumns; j++) {
col_scan = digitalRead(keycol[j]);
int keyNo = i * noOfColumns + j;
if (col_scan == LOW) {
if (keyMatrix[keyNo] == false) handleKey(keyNo);
keyMatrix[keyNo] = true;
} else {
if (keyMatrix[keyNo] == true) handleKey(keyNo);
keyMatrix[keyNo] = false;
}
}
digitalWrite(keyrow[i], HIGH);
}
}
void handleKey(int kNote){
Serial.print(kNote+LOWESTNOTE);
Serial.print("\t");
Serial.print(keyMatrix[kNote] ? "Released" : "Pressed ");
printNote(kNote);
delay(10);
}
void printNote(int key){
byte note = key % 12;
byte octave = key/12 +1;
Serial.print('\t');
Serial.print(noteNames[note*2]);
char c = noteNames[note*2+1];
if (c > ' ') Serial.print(c);
Serial.println(octave);
}F
E
D#
D
C#
C
B
A#
A
G#
G
F#