I am struggling how to read float value from inputStream. I tried before with BigDecimal, and it was not possible to get the correct number
Problem: im expecting V ~0.00 - 1.50, Later up to 55.00
While V = ~0.00, it prints 6.336931E-10, V = ~1.05 - 2.53483E-9
Java code:
DataInputStream inputStream = null;
try {
inputStream = new DataInputStream(btSocket.getInputStream());
float f = inputStream.readFloat();
System.out.println(f);
} catch (IOException e) {
e.printStackTrace();
}
To visualize sent values:
1 Answer 1
To read float values with DataInput, they need to be written in a compatible format, which is essentially a 32-bit IEEE 754 float.
Your Arduino code appears to be writing them as new-line separated decimal strings.
Those won't work together.
If you want to modify your Java to read text, something like this should work:
try (var is = btSocket.getInputStream();
var r = new InputStreamReader(is, StandardCharsets.US_ASCII);
var lines = new BufferedReader(r)) {
while (true) {
String line = lines.readLine();
if (line == null) break;
float f = Float.parseFloat(line);
System.out.println(f);
}
}
Comments
Explore related questions
See similar questions with these tags.
inputStream.skip(inputStream.available())?