Arduino Decoder

/*

Arduino Decoder: by John Coenraads This version works. No turn off delay.

=====================================

This sketch accepts MIDI commands on channel 1, decodes them and turns the appropriate IO pins on and off.

Bottom C (note 36) outputs on pin 2. Total outputs = 68 (pins 2 to 69).

If boards are daisy chained, each one can be "tuned" to a specific channel.

**This sketch handles Running Status, where the status byte is only updated when it changes.**

Equipment: Arduino Mega + MIDI shield

created 2021 APR 08, modified 2021 AUG 22

*/

// Declarations==========================================

int i, j, k; //Counters (old Fortran habit)

byte noteStatusRx, noteNumberRx, noteVelocityRx, tempVar; //Receive variables

const byte status90 = 0x90, status80 = 0x80; //Define status bytes for channel 1

//Initialize ============================================

void setup()

{

Serial.begin(31250); // Set MIDI baud rate:

while (Serial.available() > 0) {Serial.read();} //Clear serial input buffer

Serial1.end(); Serial2.end(); Serial3.end(); //Relieve ports 1,2,3 of serial IO duty

//Initialize 68 pins for output.

for (i = 2; i < 70; i++)

{

pinMode (i, OUTPUT);

digitalWrite (i, LOW);

}

}

//Main Loop =============================================

void loop()

{

while (!Serial.available()) {} //wait for serial data, port 0

tempVar = Serial.read ();

if ((tempVar == status90) || (tempVar == status80))

{noteStatusRx = tempVar;

while (!Serial.available()) {} //wait for serial data, port 0

noteNumberRx = Serial.read ();

while (!Serial.available()) {} //wait for serial data, port 0

noteVelocityRx = Serial.read ();

if (noteVelocityRx == 0) {digitalWrite (noteNumberRx - 34, LOW);}

else {digitalWrite (noteNumberRx - 34, HIGH);}

}

if (tempVar <= 0x7F) //is data byte (Running Status)

{noteNumberRx = tempVar;

while (!Serial.available()) {} //wait for serial data, port 0

noteVelocityRx = Serial.read ();

if (noteVelocityRx == 0) {digitalWrite (noteNumberRx - 34, LOW);}

else {digitalWrite (noteNumberRx - 34, HIGH);}

}

}