Let's explore sensor fusion possibilities of the compass and the accelerometer a bit further. In the previous post we used the compass to calculate the gravity vector when the accelerometer is subject to motion acceleration too. Now let's support the compass with the accelerometer and create a stabilized compass.
As we discussed before, the Earth's magnetic field is a 3D vector which has two components:
the horizontal element that points to toward the magnetic North (this
is what we use for compass) and the magnetic inclination that has
variable degree but points mostly down on the Northern Hemisphere. Now
if the magnetic sensor is not parallel to the Earth's surface, the z
component (pointing downward) of the Earth's magnetic vector is
projected into the x and y axes of the phone's magnetic sensor causing
the compass to rotate when the device is tilted. Try for example this great and popular compass application.
Point the compass toward the North then tilt the device left and right.
You will see that the compass rotates even though the longer axis of
the device (the y axis in Android API) still points toward the North Pole.
Click here to read the post further.