#include <MIDI.h>

// Create and bind the MIDI interface to the default hardware Serial port
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, midi2);

int myPins[] = {PIN_PA7, PIN_PA6, PIN_PA5, PIN_PA4, PIN_PA3, PIN_PA2, PIN_PA1, PIN_PA0, PIN_PF6, PIN_PF5, PIN_PF4, PIN_PF3, PIN_PF2, PIN_PF1, PIN_PF0, PIN_PB0, PIN_PG4, PIN_PG3, PIN_PG2, PIN_PG1, PIN_PG0, PIN_PB5, PIN_PB6, PIN_PB7, PIN_PE7, PIN_PD4, PIN_PD5, PIN_PD6, PIN_PD7, PIN_PC0, PIN_PC1, PIN_PC2, PIN_PC3, PIN_PC4, PIN_PC5, PIN_PC6, PIN_PC7};

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  Serial.print("NoteOn ");
  Serial.print("Channel:  ");
  Serial.print(channel);
  Serial.print(", Pitch:  ");
  Serial.print(pitch,HEX);
  Serial.print(", Velocity:  ");
  Serial.print(velocity,HEX);
  Serial.print(", LED number:  ");
  Serial.println(pitch-0x30);
  
  digitalWrite(myPins[constrain(pitch-0x30, 0, sizeof(myPins)/2 - 1)],HIGH);
  analogWrite(PIN_PB4, velocity*2);
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  Serial.print("NoteOff ");
  Serial.print("Channel:  ");
  Serial.print(channel);
  Serial.print(", Pitch:  ");
  Serial.print(pitch,HEX);
  Serial.print(", Velocity:  ");
  Serial.println(velocity,HEX);

  digitalWrite(myPins[constrain(pitch-0x30, 0, sizeof(myPins)/2  - 1)],LOW);
  analogWrite(PIN_PB4, 0);
}

void setup()
{
   midi2.begin(0);  // Listen to all incoming messages
   midi2.setHandleNoteOn(MyHandleNoteOn); 
   midi2.setHandleNoteOff(MyHandleNoteOff);

  pinMode(PIN_PE3, OUTPUT);
  digitalWrite(PIN_PE3, HIGH);
  
  for (int i = 0; i < sizeof(myPins)/2; i = i + 1) {
    pinMode(myPins[i], OUTPUT);
  }
  
  Serial.begin(115200);
}

void loop()
{
  midi2.read();
}
