#include <Arduino.h>
#include <MIDIKey.h>

#define KEYLENGTH	61


// UI Data
unsigned char UI_PATCH = 0;
unsigned char SEND_CH = 0;
unsigned char NOTE_SHIFT = 24;
int           BUTTONS_MODE = 0;

// Setup MIDI Keyboard Shield
void setup() 
{
	MIDIKey.begin(KEYLENGTH, 31250);		// Set Key Length & MIDI Baudrate
	MIDIKey.setHandleNote(HandleNote);  	// Set MIDI Note Handler, Put only the name of the function
	MIDIKey.setHandlePedal(HandlePedal);	// Set MIDI Pedal Handler
	MIDIKey.setHandleButton(HandleButton);	// Set MIDI Button Handler
	MIDIKey.setHandleStick(HandleStick);	// Set MIDI XYStick Handler
}

// Keyboard Scanning..
void loop()
{
	MIDIKey.Scan();
}

// Stick Function
void HandleStick(byte number, byte value)
{ 
	if (number == 0) MIDIKey.SendPitchBend(SEND_CH, value);
	if (number == 1) MIDIKey.SendControl(SEND_CH, 33, value); //33 = MOD fine controller
	if (number == 2) MIDIKey.SendControl(SEND_CH, 7, value); //7 = volume coarse
}

// Button Function
void HandleButton(byte number, byte value)
{ 
	if (value == 1) {
		if (number == 1) {
			if (UI_PATCH == 0) UI_PATCH = 127;
			else UI_PATCH--;
		} 

                if (number == 2) {
			if (UI_PATCH == 127) UI_PATCH = 0;
			else UI_PATCH++;
		}

		MIDIKey.SendProgramChange(SEND_CH, UI_PATCH);

                //if (number == 3) {
                   //add your code to run when Adv Func Button is pressed. Will need to modify line above, too...

              }		
	}
}

// Pedal Function
void HandlePedal(byte number, byte value)
{ 
	MIDIKey.SendControl(SEND_CH, 64, 127 * value);
}

// Note Function
void HandleNote(byte number, byte value, byte velocity)
{ 
	if (value == 1) MIDIKey.SendNoteOn(SEND_CH, number + NOTE_SHIFT, velocity);
	else MIDIKey.SendNoteOff(SEND_CH, number + NOTE_SHIFT, velocity);
}
