Hi. I'm trying to send integers as 2 bytes to Processing, and getting strange results. Here's the code I'm using:
Arduino:
int range = 100;
for ( int i = -range; i < range; i++ ) {
Serial.print( ( i & 0xFF ), BYTE );
Serial.println( ( i >> 8 ) & 0xFF, BYTE );
delay( 100 );
}
Processing:
void serialEvent( Serial serial ) {
strLine = serial.readStringUntil( 10 );
if ( strLine != null && strLine.length() >= 2 ) {
int msb = (int) strLine.charAt(1);
int lsb = (int) strLine.charAt(0);
int in = ( msb << 8 ) | lsb;
if ( msb >> 7 == 1 ) {
in = (int) 0xFFFF0000 | ( msb << 8 ) | lsb;
}
println( trim(strLine) + " " + in );
}
}
it sometimes works, and sometimes has very strange values. For example:
-100 becomes 83
-99 becomes -3
-98 becomes 126
-97 becomes 120
but -96 and up works fine.
It's like the Arduino isn't sending the proper characters, or Processing isn't reading them properly. Things get even weirder when I expand the range to +-500:
384 becomes 8620
385 becomes 65533
If the int contains the value 32000, sending it as two bytes requires sending two bytes. Sending it as a string requires sending 5 bytes ('3', '2', '0', '0', and '0'). If speed is critical, not needing to parse the string and convert the string back to an int can represent significant savings in time.