0

I am having an issue with trying to change the G values from the accelerator from int to float. When I simply change the variable type from int to float, it's serial output looks like this while sitting still:

-26844 -17153 -26844
mph/s: -0.17
-20133 -17217 -26844
mph/s: -0.17
-26844 -17153 -26844
mph/s: -0.17
-20133 -17217 -26844
mph/s: -0.17
-20133 -17217 -26844
mph/s: -0.17
-20133 -17217 -26844
mph/s: -0.17
-20133 -17217 -26844
mph/s: -0.17

While when it's just a plain int variable type, it looks normal:

0 0 1
mph/s: 0
0 0 1
mph/s: 0
0 0 1
mph/s: 0
0 0 1
mph/s: 0
0 0 1
mph/s: 0
0 0 1
mph/s: 0

However, I require the float version of the G values so that I can get an accurate calculation of the mph/s.

EDIT: The full code has been removed for confidential reasons.

  //we send the x y z values as a string to the serial port
  sprintf(str, "%d %d %d", xg, yg, zg);
  Serial.print(str);
  Serial.write(10);

  Serial.print("mph/s: ");
  Serial.println(mphs);

  //It appears that delay is needed in order not to clog the port
  delay(15);
}
Josh
  • 1
  • 1
  • Can you show the exact code you are using for the floating point version? Note that sprintf with %d format will not work well for them. – Patricia Shanahan Jul 08 '14 at 01:09

2 Answers2

0

In your code sample, xg, yg, zg are all floats. printf uses different format specifiers for different data types. "%d" is used for integral values, "%f" for single-precision floating point values.

Change your code to:

    //we send the x y z values as a string to the serial port
    sprintf(str, "%f %f %f", xg, yg, zg);

You can look at the other format specifiers here: printf Type Field Characters.

EDIT: It seems Arduino does not link floating point libraries by default. You need to enable them as described here: Arduino: printf/fprintf prints question mark instead of float

Community
  • 1
  • 1
metacubed
  • 7,031
  • 6
  • 36
  • 65
  • Doesn't work, it comes out like this: ? ? ? mph/s: 0.34 ? ? ? mph/s: 0.17 ? ? ? mph/s: 0.34 ? ? ? mph/s: 0.17 – Josh Jul 08 '14 at 15:15
  • Ok, that makes sense, but where exactly do I put the linker flag code? – Josh Jul 08 '14 at 17:10
0

It appears to me the problem lies with sprintf statement. You are converting float Xg, Yg and Zg as %d into sprintf().

There is an old post in Stack Overflow dealing with similar problem. Check that out.

Community
  • 1
  • 1
Quantum_VC
  • 185
  • 13