USB

The Universal Serial Bus (USB) port is found on most Arduino devices and also on the RFzero. In many ways it is used just like the Serial interface you may know from e.g. the Arduino Uno. But on the Arduino Zero and Arduino M0, Arduino Due etc. boards it is called SerialUSB instead.

Initializing the USB port

Initializing the USB port on the RFzero etc. is just like the classic Serial interface.

However, there is one drawback of the USB embedded port on the RFzero, Arduino Zero, Arduino M0 etc. boards and that is that the embedded USB port takes up to two seconds to get started. So if you want to catch the data sent by the USB port you will have to halt the program for up to two seconds.

Another way is to wait for as long as it takes for the USB port to get ready.

The drawback of waiting for the USB port to get ready is that the USB port HAS TO BE CONNECTED to a host. Otherwise it will wait forever.

The advice is to use the while (!SerialUSB) during development and testing but use the delay(2000) when the program is deployed for normal use.

Communicating via the USB port

Below is a simple “Hello World” example .

Here is an example that used both the Serial5 and USB interfaces by communicating between the them.

The above examples are rather simple but the data reception is included in the loop() function. But what if the program has to do something else? How about using an Interrupt Service Routine (ISR)? Well, ISR, USB and Arduino are really cumbersome. Fortunately, a standard Arduino function called yield() comes to rescue. In brief the yield() function is always called by the underlying Arduino environment during functions like delay() and delayMicroseconds(). So if you include it in your own slow loops and  functions you will be home safe.

But what if you don’t want to process the received data before a terminating character is received, e.g. an exclamation mark (!). The below code is an example of how to do this using a buffer to store the USB data temporarily and also using the yield() function.

The above example uses a buffer 100 bytes in size. If a larger amount of data is expected a ring buffer, with start and stop positions, that is large enough to hold the received data should be used instead.