MPU6050_light icon indicating copy to clipboard operation
MPU6050_light copied to clipboard

Suggest replacing use of math functions with float versions instead of double versions

Open DeonMarais64 opened this issue 2 years ago • 1 comments

Hi Thanks for the library, it has been most useful to me.

A suggestion if I may,

Using float version's of math functions would on some (perhaps even most) platforms result in faster execution and potentially smaller code size.

Function prototypes in math.h

double sqrt( double x );
float sqrtf( float x );

double atan2( double y, double x );
float atan2f( float y, float x );

Mixing float values with functions taking/returning double values means these need to be converted between the two, (float <-> double). Explicitly using float versions of the respective functions will ensure that the most efficient compilation and execution is achieved. Similarly, expressing literals as typed values is normally best practice (particularly with floating point types) as it makes intent clear and leaves less room for ambiguity.

void MPU6050::update(){
  // retrieve raw data
  this->fetchData();
  
  // estimate tilt angles: this is an approximation for small angles!
  float sgZ = (float)((accZ>=0.f)-(accZ<0.f)); // allow one angle to go from -180 to +180 degrees
  //float sgZ = accZ<0.f ? -1.f : 1.f; /* Less obfuscated than above ?? */
  angleAccX =   atan2f(accY, sgZ*sqrtf(accZ*accZ + accX*accX)) * (float)RAD_2_DEG; // [-180,+180] deg
  angleAccY = - atan2f(accX,     sqrtf(accZ*accZ + accY*accY)) * (float)RAD_2_DEG; // [- 90,+ 90] deg

  unsigned long Tnew = millis();
  float dt = (float)(Tnew - preInterval) * 1e-3f;
  preInterval = Tnew;

  // Correctly wrap X and Y angles (special thanks to Edgar Bonet!)
  // https://github.com/gabriel-milan/TinyMPU6050/issues/6
  angleX = wrap(filterGyroCoef*(angleAccX + wrap(angleX +     gyroX*dt - angleAccX,180.f)) + (1.f-filterGyroCoef)*angleAccX,180.f);
  angleY = wrap(filterGyroCoef*(angleAccY + wrap(angleY + sgZ*gyroY*dt - angleAccY, 90.f)) + (1.f-filterGyroCoef)*angleAccY, 90.f);
  angleZ += gyroZ*dt; // not wrapped (to do???)

}

I hope you find this useful.

DeonMarais64 avatar Dec 16 '21 04:12 DeonMarais64

Hello,

Thanks for your comment, it seems indeed to be a good suggestion. I will look for this in the future developments of the library to improve speed and efficiency.

Kind regards,

Romain

rfetick avatar Dec 16 '21 14:12 rfetick