Electronic – arduino – How to send multiple values from Processing to Arduino via Serial library

arduinoprocessingserial

I've done a basic test sending a single int value to Arduino from Processing via the Processing Serial library and all's fine. I would like to send multiple int values, but not entirely sure what's the best way to that.

Acoording to the docs Serial.write

writes bytes, chars, ints, bytes[], Strings to the serial port

so one option would be to send a string I can split and get the values:

arduino.write(intValue1+","+intValue2);

but I'm not sure how I would read the data convert when I receive it in Arduino.

Another thing that comes into mind is to use a byte[] since I'm sending multiple values, but I haven't worked with bytes much, so any advice on how pack/unpack two into a byte[] and back would be really handy.

Thanks!

Best Answer

Construct a byte array containing your data. Remember that each byte can only go up to 255, so if your int is larger than that you'll need to use multiple bytes per int.

Then on the arduino

while (Serial.available() > 0) {
  Serial.read() //now do something with this byte
}

This will loop until there are no more bytes to read, and each time it will read one byte.