see https://os.mbed.com/users/okini3939/notebook/USBHostMIDI/

Dependencies:   USBHost mbed

main.cpp

Committer:
okini3939
Date:
2018-01-03
Revision:
0:0fd787d62a99

File content as of revision 0:0fd787d62a99:

#include "mbed.h"
#include "USBHostMIDI.h"

Serial pc(USBTX, USBRX);
DigitalOut led1(LED1);
PwmOut led2(LED2), led3(LED3), led4(LED4);
USBHostMIDI midi;

volatile int sendNoteOn = -1, sendNoteOff = -1, sendControlChange = -1;

void noteOn(uint8_t channel, uint8_t note, uint8_t velocity) {
    pc.printf("noteOn %02x %02x %02x\r\n", channel, note, velocity);
    switch (note) {
    case 0:
        led2 = (float)velocity / 127.0;
        break;
    case 1:
        led3 = (float)velocity / 127.0;
        break;
    case 2:
        led4 = (float)velocity / 127.0;
        break;
    }
    sendNoteOn = (channel << 16) | (note << 8) | velocity;
}

void noteOff(uint8_t channel, uint8_t note, uint8_t velocity) {
    pc.printf("noteOff %02x %02x %02x\r\n", channel, note, velocity);
    sendNoteOff = (channel << 16) | (note << 8) | velocity;
}

void controlChange(uint8_t channel, uint8_t key, uint8_t value) {
    pc.printf("controlChange %02x %02x %02x\r\n", channel, key, value);
    switch (key) {
    case 0:
    case 0x4d:
        led2 = (float)value / 127.0;
        break;
    case 1:
    case 0x4e:
        led3 = (float)value / 127.0;
        break;
    case 2:
    case 0x4f:
        led4 = (float)value / 127.0;
        break;
    }
    sendControlChange = (channel << 16) | (key << 8) | value;
}

void midi_task(void const*) {
    int i;
    USBHostMIDI midi;
    
    // attach midi event callbacks
    midi.attachNoteOn(noteOn);
    midi.attachNoteOff(noteOff);
    midi.attachControlChange(controlChange);
    pc.printf("begin\r\n");

    for (;;) {
        // try to connect a midi device
        while(!midi.connect()) {
            Thread::wait(500);
            led1 = !led1;
        }
        Thread::wait(1000);
        midi.sendControlChange(0, 41, 127); // LED on (nanoKONTROL2)
        midi.sendNoteOn(0, 0x29, 127); // LED on (Launch Control XL)
        led1 = 1;

        for (;;) {
            if (!midi.connected()) {
                pc.printf("disconnected\r\n");
                break;
            }

            if (sendNoteOn != -1) {
                midi.sendNoteOn(sendNoteOn >> 16, sendNoteOn >> 8, sendNoteOn);
                sendNoteOn = -1;
            }
            if (sendNoteOff != -1) {
                midi.sendNoteOff(sendNoteOff >> 16, sendNoteOff >> 8, sendNoteOff);
                sendNoteOff = -1;
            }
            if (sendControlChange != -1) {
                midi.sendControlChange(sendControlChange >> 16, sendControlChange >> 8, sendControlChange);
                sendControlChange = -1;
            }
        }
    }
}

int main() {
    pc.baud(115200);
    pc.printf("*** USB Host MIDI\r\n");

    Thread midiTask(midi_task);
    for (;;) {
        Thread::wait(100);
    }
}