Major bug in Sparkfun and Kris Winer MPU-9250 AHRS code

A bit ago someone raised questions about orientation angles produced by the Sparkfun MPU-9250 breakout board, using the provided AHRS code (Sparkfun employees made their own modifications to the code posted by Kris Winer on Github).

Most of my experience is with the DLH series of sensors and the RTIMUlib Kalman filter, so I decided to buy the MPU-9250 breakout board to test it and discovered a major bug in both sets of software that produces nonsensical yaw, pitch and roll angles. It has been there for years, and others have noticed it (see issue #368 on Kris Winer’s Github page), but has not been fixed. The code has never produced useful results.

Sparkfun’s code (MPU2590BasicAHRS_I2C) doesn’t work out of the box, either, because it assumes the wrong default I2C address for their own breakout board.

Sloppy work, all the way around, and in Winer’s case it is particularly inexcusable.

The main issue is that the incorrect code inverts the handedness of the magnetometer chip coordinate system (which, due to the carrier construction, has all axes swapped relative to the accelerometer/gyro axes).

A simple fix is to negate the magnetometer Z axis data, as SHOWN CORRECTED in the line below. Note the term “-myIMU.mz”.

  MahonyQuaternionUpdate(myIMU.ax, myIMU.ay, myIMU.az, myIMU.gx * DEG_TO_RAD,
                         myIMU.gy * DEG_TO_RAD, myIMU.gz * DEG_TO_RAD, myIMU.my,
                         myIMU.mx, -myIMU.mz, myIMU.deltat);

Of course, to get useful data at all, the magnetometer MUST be correctly calibrated. So, do activate the built in calibration code, as in the modified Sparkfun example attached to this post. The calibration procedure is far from the best, and calculates only bias offsets, but works well enough to produce somewhat sensible results. For accurate results, follow the procedures described in https://thecavepearlproject.org/2015/05 … r-arduino/

In the code attached, yaw = 0 corresponds to the accelerometer/gyro X axis pointing to magnetic North, with Z up, after proper magnetometer calibration.