arduino-libraries / MIDIUSB

A MIDI library over USB, based on PluggableUSB
GNU Lesser General Public License v2.1
483 stars 89 forks source link

How to check whether the USB connection is active #46

Open tttapa opened 6 years ago

tttapa commented 6 years ago

When the MIDI connection is not active on the PC-side, there's a 250 ms timeout that blocks the entire program every time you (try to) send MIDI messages.

Is there a way to check if the connection is active beforehand? E.g. if (MidiUSB) MidiUSB.send(...);

The bool operator is declared in the header file, but it isn't yet implemented, and I couldn't find anything useful in the USB superclass that I could use.

Is there any way to resolve this issue?

Thanks, Pieter

DanielRudrich commented 5 years ago

I managed to solve this by adding a USB_Available call before sending:

Added a public method to the MIDI class: int isAvailable(); implementation: `MIDI::isAvailable() { return USB_Available(MIDI_TX);}`

In my code:

if (MidiUSB.isAvailable() == 0)
{ 
// do send stuff
}
else
{
// port not ready
}
MidiUSB.flush(); // <- this somehow needs to be outside, no idea why

Can we have this method added to the class?

warewolf commented 1 year ago

I managed to solve this by adding a USB_Available call before sending:

Added a public method to the MIDI class: int isAvailable(); implementation: `MIDI::isAvailable() { return USB_Available(MIDI_TX);}`

...snipped...

Can we have this method added to the class?

Came here because I'm having the same issue, and searched USBCDC on the Arudino Micro and essentially invented nearly the exact same code.

CDC.cpp in Arduino Core for USB CDC Serial exposes availableForWrite(), I would adopt that method name for consistency with arduino core.