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
- Prefer
TYPE_ROTATION_VECTOR: the system fuses gyroscope, accelerometer and magnetometer, so it is steady and responds quickly. Turn it into a matrix withSensorManager.getRotationMatrixFromVector. - Fallback for phones without it: accelerometer + magnetometer through
SensorManager.getRotationMatrix(R, null, gravity, geomag), each low-pass filtered first (about 0.2 per sample), or the needle jitters. - Register the magnetometer anyway, even when using the rotation vector: its
onAccuracyChangedstatus (SENSOR_STATUS_UNRELIABLE…HIGH) is the calibration signal, and the field magnitudesqrt(x²+y²+z²)in µT detects interference. Earth's field is roughly 25–65 µT; outside about 20–75 µT, warn that something magnetic is nearby. - No magnetometer means no compass; hide the feature instead of showing a dead needle.
SENSOR_DELAY_GAMEis fast enough; unregister inonPause.
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
- A light haptic tick when the heading crosses N, E, S or W.
- A bearing lock that shows "Turn right 33°" from the signed difference.
- Lock the activity to portrait: rotating the UI while you turn the phone is disorienting.
- Keep the math pure (no Android types) so it can be unit-tested with hand-built matrices: flat, tilted, and upright cases.
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.