0

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:

example value

4
  • 1
    What exactly is the purpose of inputStream.skip(inputStream.available())? Commented May 3, 2022 at 12:31
  • It doesn't change anything, I can remove it and the value won't change Commented May 3, 2022 at 12:33
  • 2
    "It doesn't change anything" does not explain why it’s there. That’s not how programming works. Don’t put random purposeless statements into your code. Besides that, any two-sided communication works by both sides having to agree about the format of the communication. Commented May 3, 2022 at 12:38
  • "V ~0.00 - 1.50, .... V = ~1.05 - 2.53483E-9" --> Is that really the right numbers: 1.50 and 1.05? IAC, more useful to print the exact output seen. Commented May 3, 2022 at 15:39

1 Answer 1

0

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);
 }
}
answered May 3, 2022 at 16:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.