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
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments