From postmarketOS

Magnetometers are a specific type of sensor found in mobile phones in order to provide compass functionality to map applications: whereas a GPS (GNSS) will only tell you where you are, a compass can tell you where you are facing.

However: magnetometers are not compasses. A magnetometer provides a three-dimensional vector of the Earth:s magnetic field. This vector is called the inclination or magnetic dip of the magnetic field. In the north these will point mostly down into the ground, in the south up in the air, and around the equator the field will be somewhat horizontal.

The magnetic inclination is measured relative to the plane of the magnetometer, which is why it is important to get the mounting matrix of the magnetometer right. This mounting matrix is commonly determined by trial-and-error with a reference device such as a stock android phone and comparing the inclination vectors on the two devices.

Magnetometer vs Compass

A compass in difference from a magnetometer, is a two-dimensional tool providing a red needle pointing north when held horizonal relative to Earth:s surface.

To get from a three-dimensional inclination vector to a two-dimensional vector to the north, we need information from an accelerometer, as this determines how the device is held relative the center of gravity of the Earth. If the accelerometer reports 1G (~9.82 Newton) on the Z axis and 0 on the X and Y axis, the device is perfectly horizontal.

To get from the inclination to e.g. compass-north, you need to perform projection of the inclination on the plane of the device. This is done using linear algebra. The process is called sensor fusion. In Linux, userspace does this fusion work. In Android, a three-dimensional geomagnetic rotation vector is calculated by fusing the magnetic inclination with the accelerometer.