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. The Arduino tutorial Lesson 4 - Serial communication and playing with data says that the Arduino stores signed ints in two bytes (16 bits). I have tried reading just two bytes of data into an 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(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.
2949173
3211317
851978
2949173
3211317
851978
2949173
3211319
How can the bytes coming from the Arduino through the serial port to integers be decoded?
valueafter each time you change it. - Thorbjørn Ravn Andersen