I am having some major problems when using the compass in the ZX plane (With the Compass mounted vertically). I have the code for the tilt compensation setup using an ADXL345 which reports Pitch and Roll accurately.
I used the equations from this source(https://jameco.com/Jameco/Products/ProdDS/2150248.pdf) for the Tilt compensation which works great in the XY plane upto +-40Degress from level. Using similar logic I have the equations to calculate the tilt compensated heading in the ZX plane which isnt as effective.
By chance do you think I have a dud module where the Z axis magneto isnt as precise as X,Y or my equations are grossly wrong.
I am calculating pitch as so
Pitch = (180 - (((float) (atan2(AccZGs, sqrt(AccYGs * AccYGs + AccXGs * AccXGs)) + M_PI) * RAD_TO_DEG)));
Roll = (180 - (((float) (atan2(AccXGs, sqrt(AccYGs * AccYGs + AccZGs * AccZGs)) + M_PI) * RAD_TO_DEG)));
and my Tilt Compensated heading by
float PitchRad = Pitch * DEG_TO_RAD;
float RollRad = Roll * DEG_TO_RAD;float ZaxisTiltCorrected = raw.ZAxis * cos(PitchRad) + raw.XAxis * sin(RollRad) * sin(PitchRad) - raw.YAxis * cos(RollRad) * sin(PitchRad);
float XaxisTiltCorrected = raw.XAxis * cos(RollRad) + raw.YAxis * sin(RollRad);
// float heading = atan2(scaled.YAxis, scaled.XAxis);
float HeadingCorrected = atan2(XaxisTiltCorrected, -(ZaxisTiltCorrected));
if (HeadingCorrected < 0)
HeadingCorrected += 2 * PI;// Check for wrap due to addition of declination.
if (HeadingCorrected > 2 * PI)
HeadingCorrected -= 2 * PI;// Convert radians to degrees for readability.
float HeadingCorrectedDegrees = HeadingCorrected * 180 / M_PI;