Code‑and.Coffee

MIDI Controlled WS2812 RGB LEDs

WS2812 LEDs Out of boredom I hooked up a strip of WS2812 RGB LEDs to the MIDI output of my Korg Electribe.

The result

The code

I used an Arduino compatible Teensy 2.0 and the FastLED library to drive the LEDs. Each LED represents one MIDI channel and the color is set in HSV (hue = note * velocity).
All black LEDs flash up white on beat and all LEDs fade to black over time.
The timing is based on the incoming MIDI clock messages.

ws2812_midi.ino

#include "Arduino.h"
#include <MIDI.h>
#include "FastLED.h"

#define LED_PIN 6
#define NUM_LEDS 16
CRGB leds[NUM_LEDS];

MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);

void setup() {
  MIDI.begin(MIDI_CHANNEL_OMNI);
  FastLED.addLeds<WS2812B, LED_PIN, BGR>(leds, NUM_LEDS);
}

int clockCount = 0;
byte isPlaying = 0;
const CRGB blendColor = CRGB(4,4,4);

void loop() {
  int note, velocity, channel, control;
  note = velocity = channel = control = 0;

  if (MIDI.read()) {
    byte type = MIDI.getType();
    switch (type) {
      case midi::NoteOn:
        note = MIDI.getData1();
        velocity = MIDI.getData2();
        channel = MIDI.getChannel();
        leds[channel].setHSV(note*velocity, 255, 255);
        break;
        
     case midi::NoteOff:
        note = MIDI.getData1();
        velocity = MIDI.getData2();
        channel = MIDI.getChannel();
        leds[channel].fadeToBlackBy(150);
        break;

      case midi::Clock:
        if (isPlaying) {
          clockCount++;
          if (clockCount%24 == 0 ) {
            clockCount = 0;
            for (int i = 0; i < NUM_LEDS; i++) {
              if (!leds[i]) leds[i] = blendColor;
            }
          }
        }
        fadeToBlackBy(leds, NUM_LEDS, 8);
        break;
      
      case midi::Start:  
        clockCount = 0;
        isPlaying = 1;
        break;

      case midi::Stop:  
        isPlaying = 0;
        break;
    }
  }
  FastLED.show();
}