Reputation: 570
Im trying to read a double from a serial port. I can read it in String, but when I parse the String to Double, the result makes no sense, and it's not the same from the String.
This is my code:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
String peso = new String (readBuffer, 0, numBytes, "UTF-8");
System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
//double d = ByteBuffer.wrap(readBuffer).order(ByteOrder.LITTLE_ENDIAN ).getDouble();
//System.out.print(d);
m_dWeightBuffer = Double.parseDouble(peso);
System.out.print(m_dWeightBuffer);
}
//System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
} catch (IOException ex) {}
break;
}
}
But now, you know how I can convert this string to Double?
System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
Output: 000.250
Good
m_dWeightBuffer = Double.parseDouble(peso);
System.out.print(m_dWeightBuffer);
Output: 0.00.0250.0
Bad
System.out.println(new String (readBuffer, 0, numBytes, "UTF-8"));
Output:
0
0
0
.250
Upvotes: 2
Views: 1441
Reputation: 550
Try doing this:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
peso += new String (readBuffer, 0, numBytes, "UTF-8").replaceAll("\\s+","").replaceAll("\\n", "").replaceAll("\\r", "");
}
} catch (IOException ex) {}
break;
}
}
Inicialize the String peso OUTSIDE of this SerialEvent method.
Upvotes: 2
Reputation: 1722
It seems the server is writing on the serial port in 4 chunks, probably 64bits words:
You are reading with a max buffer of 64 bits (readBuffer.length * 8 bits), so the last could be:
0011111111010000000000000000000000000000000000000000000000000000
Try it:
String s = "0011111111010000000000000000000000000000000000000000000000000000";
double d = Double.longBitsToDouble(Long.parseLong(s,2));
System.out.println(d); //-> 0.25
As for now nothing is wrong.
Probably you are wanting to process all 4 chunks in a single point, so you could try the following - of course, much depends on the protocol's semantics which I ignore:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
String peso = "";
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
peso += new String (readBuffer, 0, numBytes, "UTF-8");
}
m_dWeightBuffer = Double.parseDouble(peso);
} catch (IOException ex) {}
break;
}
}
That is, the double is created after all the data is read.
Upvotes: 3