/* 
 NAME:                 MIDI Program Change 
 WRITTEN BY:           TOM SCARFF
 DATE:                 9/9/2008
 FILE SAVED AS:        midi_program_change.pde
 FOR:                  Miduino ATmega168
 CLOCK:                16.00 MHz CRYSTAL                                        
 PROGRAMME FUNCTION:   Sends midi program change messages based on foot pedals pressed
 
 IMPORTANT:
 your Miduino might not start if it receives data directly after a reset,
 because the bootloader thinks you want to upload a new progam.You might 
 need to unplug the midi-hardware until the board is running your program. 
 Also when programming the Miduino disconnect the MIDI IN cable.
 
 HARDWARE NOTE:
 The Midi IN Socket is connected to the Miduino RX through an 6N139 opto-isolator
 *
 * To send MIDI, attach a MIDI out Female 180 Degree 5-Pin DIN socket to Arduino.
 * Socket is seen from solder tags at rear.
 * DIN-5 pinout is:                                         _______ 
 *    pin 2 - Gnd                                          /       \
 *    pin 4 - 220 ohm resistor to +5V                     | 1     3 |  MIDI jack
 *    pin 5 - Arduino Pin 1 (TX) via a 220 ohm resistor   |  4   5  |
 *    all other pins - unconnected                         \___2___/
 *
 */

// Constants
#define SWITCH1 14
#define SWITCH2 15
#define SWITCH3 16
#define SWITCH4 17

#define LED1 8
#define LED2 9
#define LED3 10
#define LED4 11

#define switchDebounce 30

// Variables: 
byte switches[4] = { 
  SWITCH1, SWITCH2, SWITCH3, SWITCH4 };
byte switchState[4] = { 
  HIGH, HIGH, HIGH, HIGH}; 
// Initial state of switch is high due to internal pullup
byte leds[4] = { 
  LED1, LED2, LED3, LED4 };
byte count = 0;
int Program = 64;   //  program half-way between 0 to 127
byte bypassState = LOW;     // state of bypass pedal
byte pedal = 50; // Delay for flash when pedal is pressed



byte midiByte;
byte MIDIchannel;
byte channel;
byte status=0;
byte statusType;
byte statusTest;
byte volume_now=0;
byte volume_past=0;
byte x;
byte startTest=0;
byte runningStatus;
byte Flag;
byte LedPin = 13;   // select the pin for the LED
byte runStatusFlag=0;
byte realTimeTest;
byte count_data;


void setup() {

  pinMode(4, INPUT); // Set Inputs for 4 way DIP Switch
  pinMode(5, INPUT); 
  pinMode(6, INPUT); 
  pinMode(7, INPUT); 
  digitalWrite(4, HIGH); // Set inputs Pull-up resistors High
  digitalWrite(5, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(7, HIGH);
  pinMode(LedPin,OUTPUT);   // declare the LED's pin as output

  for (x=1; x<=4; x++){
    digitalWrite( LedPin, HIGH );
    delay(300);
    digitalWrite( LedPin, LOW );
    delay(300);
  }
  //  Set MIDI baud rate:
  Serial.begin(31250);

  // Setup count and activation LEDs
  for( count = 0; count < 4; count++ ) {
    pinMode( switches[count], INPUT );          // Set pin for switches
    digitalWrite( switches[count], HIGH );      // Turn on internal pullups
    pinMode( leds[count], OUTPUT );             // Set pin for LEDs
    flashLed( leds[count], 100 ); // Flash LED
  }
}

void loop() {

  // Read 4-way DIP switch
  MIDIchannel=digitalRead(4) + (digitalRead(5)<<1) + (digitalRead(6)<<2) + (digitalRead(7)<<3);

  midiThru();

  for( count = 0; count < 4; count++ ) {
    if((digitalRead(switches[count]) != switchState[count] )&&(switchState[count] == HIGH)){
      switch( count ) {

      case 0:
        //Prev Program
        Program = Program--;
        if( Program <= 0 ){
          Program = 0; // Don't go lower than 0
        }
        midiSend( 0xC0 | MIDIchannel, Program );
        flashLed( leds[count], pedal );
        break;

      case 1:
        // Next Program
        Program = Program++;
        if( Program >= 127 ){
          Program = 127; // Don't go higher than 127
        }
        midiSend( 0xC0 | MIDIchannel, Program );
        flashLed( leds[count], pedal );
        break;

      case 2:
        // Decrement Program by 10
        Program = Program - 10;
        if( Program <=0 ){
          Program = 0; // Don't go lower than 0
        }
        midiSend( 0xC0 | MIDIchannel, Program );
        flashLed( leds[count], pedal );
        break;

      case 3:
        // Increment Program by 10
        Program = Program + 10;
        if( Program >= 127 ){
          Program = 127; // Don't go higher than 127
        }
        midiSend( 0xC0 | MIDIchannel, Program );
        flashLed( leds[count], pedal );
        break;
      }
      delay( switchDebounce );
    }
    switchState[count] = digitalRead( switches[count] );
  } 

}

//_____________________________________________________________________

//  Send a two byte midi message  
void midiSend(byte status, byte data ) {
  Serial.print(status, BYTE);
  Serial.print(data, BYTE);
}

void flashLed( byte ledPin, int flashDelay ) {
  digitalWrite( ledPin, HIGH );
  delay( flashDelay );
  digitalWrite( ledPin, LOW );
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 


void midiThru(){

  if (Serial.available() > 0){      //If MIDI available read the incoming MIDI byte and transmit it thru
    midiByte = Serial.read();
    digitalWrite(LedPin, HIGH);   // sets the LED on

    statusType= midiByte&0xF0;
    statusTest=midiByte&0x80;

    if(statusTest==0x80){        // if midi status and NOT data

      if(midiByte>=0x80 && midiByte<=0xEF){ //if midi channel command
        runningStatus=midiByte;
      }
      status=midiByte;
      Serial.print(status,BYTE); // transmit midi status byte
      txMidi();                   // transmit following data bytes
    }


    if(statusTest!=0x80&&status!=0){      // if running status and NOT starting data byte

      status=runningStatus;    // insert status byte
      statusType= status&0xF0;
      Serial.print(status,BYTE); // transmit midi running status byte
      txMidi2(status);                   // transmit following data bytes
    }

  }
  digitalWrite(LedPin, LOW);    // sets the LED off//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


void readMidi(){

  while (Flag==0){
    if (Serial.available() > 0) {  
      midiByte = Serial.read();         
      Flag=1;
    }
  }
  Flag=0;

}

////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

void txMidi(){



  if(statusType==0xF0){

    getStatus1(status);  // complete status byte

  }

  else if(statusType!=0xF0){

    getStatus2(status); // status with channel removed
  }

}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

void getStatus1(byte val){


  switch (val) {
  case 0xF0:                //Begin System Exclusive 11110000 (F0)
    while (midiByte!=0XF7){      // until End of Sysex
      if (Serial.available() > 0) {  
        midiByte = Serial.read(); 
        Serial.print(midiByte,BYTE);      
      }
    }
    break;

  case 0xF1:                //MIDI  Time Code 11110001 (F1)

    mididata1Tx();
    break;

  case 0xF2:             //Song Position Pointer  11110010 (F2) 

    mididata2Tx();
    break;

  case 0xF3:            //Song Select  11110011 (F3)

    mididata1Tx();
    break;


  case 0xF7:           //End System Exclusive 11110111 (F7)    
    break;                // single byte data

  case 0xF8:           //Timing Clock 11111000 (F8) 
    // single byte data
    break;

  case 0xFA:           //Start 11111010  (FA)
    // single byte data
    break;

  case 0xFB:          //Continue 11111011 (FB)
    // single byte data
    break;

  case 0xFC:          //Stop 11111100 (FC)
    // single byte data
    break;

  case 0xFE:          //Active Sensing  11111110 (FE)
    // single byte data
    break;

  case 0xFF:         //System Reset 11111111 (FF) 
    // single byte data  
    break;




  default:
    break;
  }
}

//___________________________________________________

void getStatus2(byte val){

  val = val & 0xF0;          //remove channel info

  switch (val) {
  case 0x90:                // Note-On Event            1001bbbb (9X) 

    mididata2Tx();
    break;

  case 0x80:                //Note-Off  Event          1000bbbb (8X)

    mididata2Tx();
    break;

  case 0xA0:                //Control Polyphonic Key Pressure  1010bbbb (AX)      0kkkkkkk  0fffffff

    mididata2Tx();  
    break;

  case 0xB0:                //Control Change           1011bbbb (BX)

    mididata2Tx();   
    break;

  case 0xC0:                //Program Change           1100bbbb (CX)

    mididata1Tx(); 
    break;

  case 0xD0:                //Channel Pressure         1101bbbb (DX)

    mididata1Tx();  
    break;

  case 0xE0:                //Pitch Bend               1110bbbb (EX)

    mididata2Tx();   
    break;


  default:
    break;
  }
}


////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

void txMidi2(byte val){      // running status mode data 1 available already in midiByte


  val = val & 0xF0;          //remove channel info

  switch (val) {
  case 0x90:                // Note-On Event            1001bbbb (9X) 

    Serial.print(midiByte,BYTE); // transmit midi data
    mididata1Tx(); 
    break;

  case 0x80:                //Note-Off  Event          1000bbbb (8X)

    Serial.print(midiByte,BYTE); // transmit midi note data
    mididata1Tx();
    break;

  case 0xA0:                //Control Polyphonic Key Pressure  1010bbbb (AX)      0kkkkkkk  0fffffff

    Serial.print(midiByte,BYTE); // transmit midi Polyphonic Key Pressure  data 1
    mididata1Tx();   
    break;

  case 0xB0:                //Control Change           1011bbbb (BX)

    Serial.print(midiByte,BYTE); // transmit midi control data 1
    mididata1Tx();   
    break;

  case 0xC0:                //Program Change           1100bbbb (CX)

    Serial.print(midiByte,BYTE); // transmit midi program change data  
    break;

  case 0xD0:                //Channel Pressure         1101bbbb (DX)

    Serial.print(midiByte,BYTE); // transmit midi channel pressure data     
    break;

  case 0xE0:                //Pitch Bend               1110bbbb (EX)

    Serial.print(midiByte,BYTE); // transmit midi Pitch Bend  data 1
    mididata1Tx();    
    break;


  default:
    break;
  }
}

//---------------------------------------------------------------------------------

void mididata2Tx()

{
  count_data=2;
  while (count_data!=0){
    readMidi();             // get midi 
    realTimeTest=midiByte&0x80;   // if Real Time dont decrement count
    if (realTimeTest==0){
      count_data=count_data-1;
    }            // data byte
    Serial.print(midiByte,BYTE); // transmit midi 
  }

}    

//------------------------------------------------------------------------------

void mididata1Tx()

{
  count_data=1;
  while (count_data!=0){
    readMidi();             // get midi 
    realTimeTest=midiByte&0x80;   // if Real Time dont decrement count
    if (realTimeTest==0){
      count_data=count_data-1;
    }            // data byte
    Serial.print(midiByte,BYTE); // transmit midi 
  }

}