📚 Encyclopedia

Android · updated 2026-11-02

A compass on Android sensors (heading, tilt, calibration, true north)

androidsensorscompassmagnetometerrotation-vectorgeomagneticfieldkotlin

A phone compass is a rotation matrix plus a few details that decide whether it feels right: which axis counts as "forward", how to smooth an angle, and how to tell the user the magnetometer is lying. This comes from Justin's Compass app (io.jhampton.compass, Kotlin + Compose, 2026-10-27).

Which sensors

Heading that works flat and upright

SensorManager.getOrientation gives azimuth for the phone's top edge, which is right when the phone lies flat and meaningless when it is held upright to look through the camera. Flipping to the camera axis at 45° of tilt makes the needle jump.

Instead, take the device→world matrix R (row-major, world = East, North, Up) and project the vector device Y minus device Z onto the horizontal plane:

east  = R[1] - R[2]
north = R[4] - R[5]
heading = atan2(east, north)   (degrees, normalized to 0..360)

Flat, device Z points up and contributes nothing horizontal, so this is the top edge. Upright, device Y points up and −Z (out of the back camera) is horizontal, so this is the camera direction. In between it blends smoothly. When the horizontal length hypot(east, north) drops below about 0.15 (phone pointing straight up or down) there is no meaningful heading; hold the last value.

Tilt for a bubble level comes from the last row of R, which is "up" in device coordinates: asin(R[6]) and asin(R[7]) are the side-to-side and top-to-bottom tilts.

Smoothing an angle

Never average degrees directly: 359° and 1° average to 180°. Low-pass the sine and cosine separately and take atan2 of the result. The same wraparound applies to the UI: rotate the dial by the shortest signed difference from its last angle (((to − from) mod 360), mapped to −180..180) so passing north turns it 2°, not 358°.

True north

A magnetometer gives magnetic north. Android ships the World Magnetic Model: GeomagneticField(lat, lon, altitudeM, timeMs).declination is degrees east of true north; add it to the magnetic heading. It needs a location, so ask once and keep a magnetic-only mode when location is denied. LocationManager (no Play Services) is enough; a last-known fix works because declination changes slowly across distance. The magnetic model and sun-position formulas are science topics; on Android, declination is only this one call. (The app computes the sun with NOAA low-precision formulas, a pure function unit-tested against known solstice noon and sunset times.)

Small things that make it feel right

Testing without a phone

The emulator's extended controls (or adb emu sensor set) feed fake rotation and magnetic values, and adb emu geo fix <lon> <lat> sets a location. That verifies math and UI; real magnetometer noise, calibration prompts and haptics still need a real phone.

See also

Sources: compass memory, repo ~/dev/compass (0.1.0), tldr post #1860