-
Notifications
You must be signed in to change notification settings - Fork 5
USB message passing
The RoboRIO can send information to the Arduino across the USB cable that connects them together. The Arduino can use that information to change the way it behaves, such as to change the bling pattern to let the driver know something happened, or enhance the image of our robot with cool effects.
The simplest message to send is a byte, which in our case is 8 binary bits of data, representing an integer from 0 to 256. If we create multiple bling "animations", we can assign a number to each one, and the RoboRIO can select the animation it wants by sending the byte that represents that number.
We will use the SerialPort API to open a channel to the Arduino. It will be connected to the SerialPort.Port.kUSB port, at a baud rate of 9600 bits per second. This is a common, standard baud rate that is reliable and fast enough for our task.
public SerialPort(int baudRate,
SerialPort.Port port)
Create an instance of a Serial Port class. Defaults to 8 databits, no parity, and one stop bit.
To send data to the Arduino, we will use this API, assuming the SerialPort is instantiated as m_arduino:
static final byte[] MESSAGE = "1".getBytes(); // Create a one character message for each bling
m_arduino.write(MESSAGE, MESSAGE.length); // Send the bling message to the Arduino
In the setup() function, we need to initialize the Arduino side of the serial port:
Serial.begin(9600);
Then, in the loop we need to check if there is a byte available from the RoboRIO, and if there is then read it and change bling modes.
while (Serial.available() > 0)
{
messageByte = Serial.read();
}
Finally, we can decide what to do based on the received message byte:
switch (messageByte)
{
case '1':
blingMode = BLUE_LEDS;
break;
case '2':
blingMode = RED_LEDS;
break;
...
default:
// The byte was not for a valid message, so we ignore it...
}
And we continue the loop with different bling functions:
if (blingMode == BLUE_LEDS)
{
blue_led_function();
}
else if (blingMode == RED_LEDS)
{
red_led_function();
}
/* etc. */