The code is currently designed for more than 4 buttons, but I only have 4 connected.
Basically whats happening here is when a button is pressed it sends a few MIDI Note On signals, when it's released, it sends corresponding Midi Note Off signals.
I can't see any reason why Pin 5 specifically would be erratic.
#include "MIDIUSB.h"
//Major Chords
int allChords[18][4] = { {51, 55, 58, 62}, //Majors/7ths Eb
{58, 62, 65, 69}, //Bb
{53, 57, 61, 65}, //F
{60, 64, 67, 71}, //C
{55, 59, 62, 66}, //G
{50, 54, 57, 61}, //D
{57, 61, 64, 68}, //A
{52, 56, 59, 63}, //E
{59, 63, 66, 70}, //B
{51, 54, 58, 51}, //Minors Eb
{58, 61, 65, 58}, //Bb
{53, 56, 60, 53}, //F
{60, 63, 67, 60}, //C
{55, 58, 62, 55}, //G
{50, 53, 57, 50}, //D
{57, 60, 64, 57}, //A
{52, 55, 59, 52}, //E
{59, 62, 66, 59} //B
};
//Eb Bb F C G D A E B
//Major, Minor, 7th
const int buttonPin[] = {2,3,4,5};
const int ledPin = 13;
int chanVel = 100;
int buttonState[27] = {};
void setup() {
pinMode(ledPin,OUTPUT); //set LED Pin to output
for (int i=0; i<27; i++){
pinMode(buttonPin[i], INPUT_PULLUP); //set all pins as input pullups
buttonState[i] = 0; //set all button states to off
}
}
void noteOn(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOn);
}
void noteOff(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOff);
}
void loop() {
for (int i=0; i<4; i++){ // read every pin and check if its H/L
if(digitalRead(buttonPin[i]) == LOW && buttonState[i] == 0){
if (i < 18){
noteOn(0,allChords[i][0],chanVel);
noteOn(0,allChords[i][1],chanVel);
noteOn(0,allChords[i][2],chanVel);
MidiUSB.flush();
}
else {
noteOn(0,allChords[i-18][0],chanVel);
noteOn(0,allChords[i-18][1],chanVel);
noteOn(0,allChords[i-18][2],chanVel);
noteOn(0,allChords[i-18][3],chanVel);
MidiUSB.flush();
}
buttonState[i] = 1;
}
else if (digitalRead(buttonPin[i]) == HIGH && buttonState[i] == 1) {
if(i < 18) {
noteOff(0,allChords[i][0],chanVel);
noteOff(0,allChords[i][1],chanVel);
noteOff(0,allChords[i][2],chanVel);
MidiUSB.flush();
}
else {
noteOff(0,allChords[i-18][0],chanVel);
noteOff(0,allChords[i-18][1],chanVel);
noteOff(0,allChords[i-18][2],chanVel);
noteOff(0,allChords[i-18][3],chanVel);
MidiUSB.flush();
}
buttonState[i] = 0;
}
}
}