简体   繁体   中英

Converting G values into floats from an Arduino accelerometer

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);
}

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM