Please excuse me. I acknowledge the fact that I’m being a dick.
Okay, so the video sort of annoyed me. Don’t get me wrong, Sam was great explaining the stuff for beginners - it’s just that the code itself annoyed me.
So I may have tweaked it to be a bit more concise, and a bit more effecient in terms of memory. Sorry.
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
//const makes things read only when declared.
//Attempting the change this programmatically will cause compile errors
//
//This is a map between pin and midi node code.
const struct _MidiButton
{
int pin;
int midinote;
} g_midi_buttons[] = {
{ 2, 36},
{ 3, 38},
{ 4, 40},
{ 5, 41},
{ 6, 43},
{ 7, 45},
{ 8, 47},
{ 9, 48},
{ 10, 50},
{ 11, 52},
{ 12, 53},
};
//Declare the array where we will store the states for all the buttons
//The size thingy causes the compiler to make the array big enough to store the
//states for all the buttons declared above in the map.
bool g_buttonStates[ sizeof(g_midi_buttons) / sizeof(g_midi_buttons[0]) ] = {0};
void setup()
{
MIDI.begin(); //BEINNINFG IDIU TGHUBGS
//Go through (loop through) the map of buttons and set them all to pin up
//INPUT_PULLUP means the pin is in input mode with an internal pull up resistor, so it is waiting to receive ground to do something
const size_t numButtons = sizeof(g_midi_buttons) / sizeof(g_midi_buttons[0]);
for(size_t x=0; x < numButtons; ++x)
{
pinMode(g_midi_buttons[x].pin, INPUT_PULLUP);
//Also initialise the state for the current button so that it is marked as 'off'
g_buttonStates[x] = false;
}
}
void loop()
{
//go through all the buttons, reading their current status and
//handling button up/down events
const size_t numButtons = sizeof(g_midi_buttons) / sizeof(g_midi_buttons[0]);
for(size_t x=0; x < numButtons; ++x)
{
int state = digitalRead(g_midi_buttons[x].pin);
// ! is not - you could also use !g_buttonStates[x], but == false is more readable
if((state == LOW) && (g_buttonStates[x] == false))
{
MIDI.sendNoteOn(g_midi_buttons[x].midinote, 127, 1); //turn midi note on velocity 127, midi channel 1.
//Mark the button state as TRUE, since the button is now on
g_buttonStates[x] = true;
}
else if((state == HIGH) && (g_buttonStates[x] == true))
{
MIDI.sendNoteOff(g_midi_buttons[x].midinote,0,1); //turn midi note off, midi channel 1.
//Mark the button state as FALSE, since the button is now on
g_buttonStates[x] = false;
}
}
}