I want to send integer values from my Arduino to a java application. To do so I am using a serial port. In the processing program for the Arduino I am printing the following to the serial port:
Serial.print(accel, DEC)
Accel is a signed int. In my java code I am implementing a SerialPortEventListener and I am reading an array of bytes from the inputstream input.
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
byte[] chunk = new byte[available];
input.read(chunk);
System.out.println (new String(chunk));
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
I need to convert this array of bytes into integers, but I am not sure how to do this. This Arduino tutorial (http://www.ladyada.net/learn/arduino/lesson4.html) says that the Arduino stores signed ints in 2 bytes (16 bits). I have tried reading just 2 bytes of data into array chunk and then decoding those two bytes into integer with the following code.
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
int n = 2;
byte[] chunk = new byte[n];
input.read(chunk);
int value = 0;
value |= chunk[0] & 0xFF;
value <<= 8;
value |= chunk[1] & 0xFF;
System.out.println (new String(chunk));
System.out.println(value);
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
This should print out a stream of integers fluctuating between -512 and -516 but it doesn’t. The code prints out the following : -5 2949173 12 3211314
851978 -5 2949173 12 3211314
851978 -5 2949173 12 3211314
Can someone please help me decode the bytes coming from the Arduino through the serial port to integers? Thanks.