Tilt Compensated HMC5883L in the ZX Plane (Vertically Mounted)

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;

The original equations assume that the Z axis is pointing mostly down.

They can be rewritten assuming that any other axis points down. Just make the appropriate cyclic substitution from the three possibilities:

XYZ -> ZXY -> YZX

I didn't check yours, but if your equations are correct and it still doesn't work well, the magnetometer needs calibration.

I have proceeded using the same logic as you mentioned for the equations. I also have working code for offset calculations/calibration. I haven't used them together so maybe i will try that and report back.