Skip to content

Instantly share code, notes, and snippets.

@brunodmt
Last active December 13, 2015 20:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunodmt/4969611 to your computer and use it in GitHub Desktop.
Save brunodmt/4969611 to your computer and use it in GitHub Desktop.
Simple script to control LEDs with an Arduino connected to a USB MIDI Keyboard, more info at http://blog.brunodemartino.com.ar/2013/02/arduino-midiled/ Script simple para controlar LEDs con un Arduino conectado a un teclado MIDI USB, más información en http://blog.brunodemartino.com.ar/2013/02/arduino-midiled/
#include <Usb.h> // Librería USB Host Shield V2
#include <usbh_midi.h> // Librería USBH MIDI
USB Usb;
MIDI Midi(&Usb);
/*
* Constantes de configuración
* La cantidad de notas debe ser igual a la cantidad de LEDs, además las salidas deben soportar PWM
*/
const int notaInicial = 0x3C; // Primer nota a procesar
const int notaFinal = 0x3E; // Última nota a procesar
const int ledInicial = 44; // Pin del primer LED
const int ledFinal = 46; // Pin del último LED
void setup()
{
// Inicializar el puerto Serie (sólo para debug, se puede desactivar)
Serial.begin(115200);
// Inicializar los pins de los LED en modo salida
for(int i = ledInicial; i <= ledFinal; i++) {
pinMode(i, OUTPUT);
}
// Esperar hasta que se incialice el dispositivo USB
if (Usb.Init() == -1) {
while(1);
}
// Delay para evitar incovenientes con el USB
delay( 200 );
}
void loop()
{
// Procesar USB
Usb.Task();
// Si la conexión está establecida y anda todo OK...
if( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
// Procesar los datos MIDI
MIDI_poll();
}
// Esperar 1 para que no explote
delay(1);
}
// Función Mágica!!
void MIDI_poll()
{
// Definir el buffer para recibir el comando MIDI
byte outBuf[3];
// Si recibimos algo...
if( Midi.RcvData(outBuf) == true ){
// Calcular el pin del LED en base a la nota recibida
int led = map(outBuf[1], notaInicial, notaFinal, ledInicial, ledFinal);
// Si dio un valor en el intervalo válido
if(led >= ledInicial && led <= ledFinal) {
// Si el comando es NoteOn (0x9n)
// Entonces el brillo del LED (entre 0 y 255) debe calcularse según la velocidad (tercer byte, entre 0 y 128)
// Si no, apagar el LED
int value = (outBuf[0] == 0x90) ? map(outBuf[2], 0, 128, 0, 255) : 0;
analogWrite(led, value);
}
// Enviar los 3 bytes en hexadecimal por puerto Serie (sólo para debug, se puede desactivar)
Serial.print(outBuf[0], HEX);
Serial.print(outBuf[1], HEX);
Serial.print(outBuf[2], HEX);
Serial.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment