0

I've been trying to follow this example code for interfacing my atmega328P with Mpu6050: https://www.instructables.com/Accelerometer-MPU-6050-Communication-With-AVR-MCU/

And was wondering a couple of things. First of all, the sensors on an MPU6050 are 16-bit, which means that each sensor value such as Ax, Ay etc. are 2 byte each (8-bit + 8-bit = 16-bit = 2 bytes).

The code itself reads from the following line when obtaining the values: AcX = Wire.read()<<8 | Wire.read(); where the MSB (8-bit) are first read, and then the LSB (8-bit); which gives us 2 bytes.

So what I don't understand is why he uses float values for storing the sensor-data and not a 16-bit int? Since Floats are 4 byte long; won't that just add a bunch of zeros to the obtained 2 bytes?

2
  • In your second question, what do you mean by "data lost"? Is the information transferred with its full-precision?
    – JRobert
    Commented Jun 26, 2021 at 11:45
  • 3
    The code snipped you show seems to have been written by someone who doesn't know what they are doing. Do not pay too much attention to it. Commented Jun 26, 2021 at 12:27

2 Answers 2

1

In the instructables code he's using a float because he wants to scale the value to a range of ±2g. The values the accelerometer gives are not the actual values but, like the Arduino's ADC, a representation of the value using a range. By dividing that representation by 16384 you get the actual G value, which is a decimal value.

That value can be more useful than the raw data.

As for that other snippet of code you provide, it cannot work. Not only does it use global variables that don't exist, but it returns a value from a void function which cannot happen. I don't know quite what it hopes to achieve.

1
  • Floats aren't that simple. The conversion to float happens at the moment of division. The bytewise combining is done in an int. It can't be done in a float because a float doesn't represent the value in that kind of way. If you then assign a float to a byte it will be a byte and any decimal portion will be discarded.
    – Majenko
    Commented Jun 26, 2021 at 17:38
1

We can't know this writer's reasons, but a typical reason why someone might use floats vs. ints is that they prefer not to manage the binary-point location and any possible overflows during the following calculations. Instead, they are willing to accept the tradeoff of execution-time vs. programming time, and the increased memory requirements (both RAM and Flash) of letting the floating-point library do it for them.

Update:

Or, as implied elsewhere, the programmer doesn't know how to calculate with integer arithmetic (which to be fair, is a little more complicated than just writing out the formula).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.