This question is about an algorithm, not a specific language.
I have a mobile device, with the following axis -
When the device is pointed perpendicular to the ground (Positive Z facing up), I get an accurate reading of the compass in degrees with the angle being between north and the positive Y of the device. So if I hold the device and point it west, I will get either the value 270 or the value -90 (not quite sure how to figure out which one I'll get). When I hold the device with Y pointing towards the sky, the compass is no longer accurate BUT I can use the device accelerometer to figure out when that is the case AND I can use the gyro to figure out what the rotation of the device is.
So, when I get an accurate reading of the compass, I am saving a parameter called "lastAccurateAttitude", which is the Quaternion from the gyro. I also save "lastAccurateHeading" as the angle from north.
What I am attempting to do is use lastAccurateHeading, lastAccurateAttitude and the current attitude, to calculate the angle between the north and the negative z axis of the device. Right now, I am stuck on the math, so I would appreciate some help.
If possible, I would love for this to also work when either x, -x, y or -y of the device are pointing upwards. (The north would still be calculated compared to -z).