• That's a cool hack. What we call Q&D (quick and dirty).
    Aran2 gives -180 to 180.
    theta=atan2(z,x)
    if(theta<0) theta+=360. Then theta ranges from 0 to 360
    For the left handed axis on this chip theta= atan(-z/x)

    Using the accelerometer readings gx, gy, gz
    theta = atan2(gz,gx), phi=atan2(gz,gy)
    rotate around yaxis
    x1=gx, y1=cos(theta)*gy-sin(theta)*gz, z1=sin(theta)*gy+cos(theta)*gz
    the rotate around the xaxis
    x2=cos(phi)*x1+sin(phi)*z1, y2=y1, z2=-sin(phi)*x1+cos(phi)*z1
    At which point z2 should be -1. X2 and Y2 should be zero
    If the rotations are them applied to the magnetometer readings the compass can be leveled.
    Some gotchas:
    May need a minus sign in the atan2(-a/b)
    May need to rotate the opposite direction by changing the sign on the sin terms( +sin becomes -sin, and -sin becomes +sin)
    I captured some data earlier this morning and did some of this in a spreadsheet. It looks like it works but I want to finish the mounting fixture and change the code to load the zero calibrations rather than recalibration on each run.

                         X  Y   Z   atan2(x/z)  atan2(y/z)
    

    Acceleration -0.000249863 0.003465652 1.000553131 -0.014308162 0.198456693

About