/* 
  Control 5 WS2811 RGB LEDs using Ableton Live and USB MIDI
  Board - Teensy 3.1
  By Rishi Franklin
  
  v1.0 - Basic functionality
  This example code is in the public domain.
*/

#include <Adafruit_NeoPixel.h>

#define NUMBER_OF_LEDS    5
#define DIN               2

Adafruit_NeoPixel pixel = Adafruit_NeoPixel(NUMBER_OF_LEDS, DIN, NEO_GRB + NEO_KHZ400);

uint16_t R = 0;
uint16_t G = 0;
uint16_t B = 0;

uint16_t pix[NUMBER_OF_LEDS] = {0, 1, 2, 3, 4};

// Assign channel numbers to midi tracks in Ableton Live
// Name them for simplicity

#define KICK_DRUM    5
#define SNARE        3
#define PERC_1       2
#define PERC_2       4
#define LEAD         1


uint16_t ChannelToPixel(byte ch) {
  switch(ch) {
   case LEAD:       return pix[0]; break;
   case PERC_1:     return pix[1]; break;
   case SNARE:      return pix[2]; break;
   case PERC_2:     return pix[3]; break;
   case KICK_DRUM:  return pix[4]; break;
   default:         return 0;
  } 
}

void setup() {

  pixel.begin();
  pixel.show();
  
  randomSeed(analogRead(0));
   
  usbMIDI.setHandleNoteOff(OnNoteOff);
  usbMIDI.setHandleNoteOn(OnNoteOn);

}

void loop() {
  usbMIDI.read(); // USB MIDI receive
  
  R = random(0, 254);
  G = random(0, 254);
  B = random(0, 254);

}

void OnNoteOn(byte channel, byte note, byte velocity) {
  pixel.setPixelColor(ChannelToPixel(channel), pixel.Color(R, G, B));
  pixel.show();
}

void OnNoteOff(byte channel, byte note, byte velocity) {
  pixel.setPixelColor(ChannelToPixel(channel), pixel.Color(0, 0, 0));
  pixel.show();
}