With OS 5.9 I was using USBDevice - a | Mbed library to receive MIDI messages as USBDevice was not included in 5.9. OS 5.15 now has USBDevice included so the Kojto library is no longer needed. However, the two libraries handle callbacks differently. The code I used previously no longer works.
There are plenty of examples of how to write callbacks for the Kojto library but I was unable to find a single example of how to write a callback for the 5.15 library.
The following code is able to receive MIDI messages thru a callback function. Please let me know how this might be improved. Thanks.
<>
/* mbed Microcontroller Library
-
Copyright (c) 2019 ARM Limited
-
SPDX-License-Identifier: Apache-2.0
-
mbed-os 5.15.1
*/
#include âmbed.hâ
#include âplatform/mbed_thread.hâ
#include âUSBMIDI.hâ
// Blinking rate in milliseconds
#define BLINKING_RATE_MS 500
// Will use âpcâ for printf
Serial pc(SERIAL_TX, SERIAL_RX);
// Initialise the digital pin LED1 as an output
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
MIDIMessage midimsg;
USBMIDI *pMidi;
void MidiCallback(void)
{
pMidi->read(&midimsg);
led3 = !led3;
//printf statement will cause a hang
//printf("%02x\n\r", midimsg.type());
switch (midimsg.type())
{
case MIDIMessage::NoteOnType:
break;
case MIDIMessage::NoteOffType:
break;
case MIDIMessage::ControlChangeType:
break;
case MIDIMessage::PitchWheelType:
break;
case MIDIMessage::SysExType:
led1 = !led1;
break;
default:
break;
}
}
int main()
{
// Initialization for printf
pc.baud(115200);
fclose(stdout);
stdout = pc;
fclose(stderr);
stderr = pc;
// Init Midi
printf("init midi\n\r");
USBMIDI midi;
pMidi = &midi;
printf("midi defined\n\r");
midi.attach(MidiCallback); // call back for MIDI messages received
while (true) {
led2 = !led2;
thread_sleep_for(BLINKING_RATE_MS);
// print the midimsg to see if MidiCallback found something
printf("%02x,%02x,%02x,%02x,%02x,%02x\n\r", midimsg.type(), midimsg.data[0],
midimsg.data[1], midimsg.data[2], midimsg.data[3], midimsg.data[4]);
}
}
>
<