1. Overview
A phone contains three small MEMS sensors that matter here: a gyroscope (angular rate), an accelerometer (specific force, which at rest points opposite to gravity) and a magnetometer (the Earth's magnetic field plus local disturbances). None of them alone gives a good orientation: the gyroscope is smooth and fast but drifts when integrated; the accelerometer gives an absolute vertical but is noisy and confused by any linear acceleration; the magnetometer gives an absolute heading but is easily disturbed by metal and electronics.
Sua Geometry combines them with a complementary filter on unit quaternions that runs at the sensor rate (200 Hz), and then produces the output at a lower, user-selected rate (1–50 Hz) through a window mean — which acts as an anti-aliasing decimator — and a dynamic SLERP low-pass filter. All the displayed quantities (Euler angles, heading, plane angle, level) are computed from that filtered quaternion.
2. Frames and conventions
Device frame B (Android convention): x points to the right of the screen, y to the top of the screen and z out of the screen, towards the user [18]. This frame does not change when the interface rotates, which is one reason the app is locked in portrait.
Local frame W: East–North–Up (ENU), a local-level frame that is treated as inertial for these short measurements (the Earth's rotation, 15°/h, is below the noise of phone gyroscopes). A Hamilton unit quaternion q = (w, x, y, z) rotates vectors from the device into the world [1, 6]:
Angles are handled internally in radians and converted to degrees only for display. Positive angles follow the right-hand rule unless a measurement explicitly says “clockwise”.
3. Representing attitude
A rotation by an angle θ about a unit axis ê is represented by the unit quaternion [1, 4]:
Composition of rotations is the Hamilton product, with scalar part w and vector part v:
The equivalent rotation matrix, used here only to explain the formulas and to initialise the filter, is [2, 3]:
Why quaternions? They have no singularities (Euler angles lose a degree of freedom at ±90° of pitch, the “gimbal lock”), they compose with 16 multiplications, they are renormalised with a single square root, and they interpolate naturally on the sphere (SLERP). q and −q represent the same rotation; the engine always chooses the sign that keeps consecutive quaternions in the same hemisphere. The continuous kinematics with body angular rate ω is [5, 6]:
Code: core/quaternion.hpp (product, rotation of vectors, exponential map, SLERP, conversion from a matrix by Shepperd's method [7]).
4. Sensor models
With R = R(q) (device → world), the measurements are modelled as [16, 17]:
fB is the specific force: at rest it equals g times the world vertical expressed in the device, i.e. it points up (Android convention [19]). b are slowly varying biases, n white noise and d a magnetic disturbance (hard- and soft-iron effects, nearby metal). Android delivers TYPE_ACCELEROMETER, TYPE_GYROSCOPE and TYPE_MAGNETIC_FIELD already factory-calibrated and, for the gyroscope and magnetometer, with the system's own bias compensation [19, 20, 22]; Sua Geometry adds its own bias estimate at rest (section 8), the disturbance detection of section 7 and the level calibration of section 13.
The engine requests 200 Hz for the accelerometer and gyroscope (5 ms) and 100 Hz for the magnetometer through ASensorEventQueue_registerSensor [21]. 200 Hz is the highest rate that does not require the HIGH_SAMPLING_RATE_SENSORS permission on Android 12 and later. Each batch of events is sorted by timestamp before it is processed.
5. Gyroscope prediction
Between two gyroscope samples the angular rate is assumed constant, and the kinematics of section 3 is integrated exactly with the exponential map [6]:
where b̂ is the estimated bias. For very small angles the series expansion cos(θ/2) ≈ 1 − θ²/8, sin(θ/2)/θ ≈ 1/2 − θ²/48 avoids dividing by zero. The quaternion is renormalised after each step. Intervals longer than 100 ms (a pause in the sensor stream) are not integrated.
Code: AttitudeFilter::onGyro, expRot.
6. Tilt correction (accelerometer)
The filter follows the structure proposed by Valenti, Dryanovski and Xiao [10], a member of the family of complementary filters on SO(3) of Mahony et al. [8] (see also the gradient-descent filter of Madgwick et al. [9]). The measured “up” direction is rotated into the world with the predicted orientation and compared with the true vertical ẑ:
The axis n is always horizontal, so this correction can never change the heading. A fraction α of the full correction is applied:
Applying the rotation of angle α·θ about n is exactly a SLERP between the identity and the full correction. The adaptive factor f(e) suppresses the correction when the magnitude of the measured force differs from g, i.e. when there is linear acceleration [10]:
τa = 1 s in normal operation and 0.05 s during the first 1.5 s, so the filter converges quickly when the app starts. The first accelerometer sample initialises the tilt directly.
Code: AttitudeFilter::onAccel.
7. Heading correction (magnetometer)
Only the rotation about the vertical is corrected, so a magnetic disturbance can never alter the tilt [10]. The measured field is rotated into the world and its horizontal component is turned towards magnetic north (+y of ENU):
τm = 2 s. A magnetometer sample is rejected as disturbed when its magnitude differs by more than 12 % from a slowly adapting reference, when the angle between the field and the vertical (the magnetic dip) changes by more than 6°, or when |m| is outside 15–90 µT (the Earth's field is about 25–65 µT [24]). The references adapt with a 15 s time constant, so a new, stable environment is eventually accepted. When the compass is switched off, the heading is driven by the gyroscope alone: the tilt remains exact and the heading becomes relative.
Code: AttitudeFilter::onMag, correctYaw.
8. Gyroscope bias at rest
The phone is declared still when the corrected angular rate stays below 0.03 rad/s and the accelerometer barely changes for 0.5 s. While still, the raw gyroscope reading is averaged:
The weight max(1/n, Δt/(τb+Δt)) makes it a cumulative mean at first (fast and optimal for a constant bias) and an exponential mean with memory τb = 10 s afterwards. The estimate is limited to 0.1 rad/s. A residual bias β produces a steady tilt error of about β·τa, so this step matters: in the tests, a 0.2°/s bias that would cause a 0.2° tilt error is reduced to a few hundredths of a degree within seconds.
9. Output stage
9.1 Window mean
The output rate f = 1/T is chosen by the user (1, 3, 10, 25 or 50 Hz). Windows follow a fixed rhythm (the deadline advances by exactly T), so the output does not drift below its nominal rate. All the quaternions of a window are summed with their signs aligned and normalised — the chordal mean. For orientations that are close to each other it agrees to second order with the optimal quaternion average of Markley et al. [12], at O(1) cost and without storing samples. The same sum yields the angular dispersion σ of the window:
9.2 Noise reduction
For white noise, averaging N samples divides the standard deviation by √N. For the tilt, with accelerometer noise σa:
Example: σa = 0.02 m/s² gives 0.12° per sample; at 3 Hz (N ≈ 67) the window mean reduces it to about 0.014°. At 50 Hz (N = 4) it is about 0.06°, which is why the lower rates are recommended for precise static measurements.
9.3 Anti-aliasing
Taking a single sample every T seconds would fold any vibration above f/2 into the output (aliasing). Averaging the N samples of the window first is a moving-average decimator — the first-order case of the cascaded integrator-comb filters of Hogenauer [14, 15] — whose frequency response at frequency ν is:
In the engine tests, a 0.5° vibration sampled at 3 Hz leaves 0.03° at 9 Hz, 0.07° at 10.5 Hz and 0.04° at 37 Hz in the output, instead of up to the full 0.5° that point sampling would show. The SLERP filter that follows attenuates it further.
9.4 Dynamic SLERP filter
Spherical linear interpolation, introduced for rotations by Shoemake [11], moves along the great arc between two unit quaternions:
A first-order low-pass filter on the rotation group is obtained by moving from the previous output towards the new window mean by a fraction α each period:
τ is the “Smoothing” setting (off, 0.5, 1, 3 or 10 s). The dynamic part avoids lag when the phone is moved: δ is the angle between the previous output and the new mean, and the thresholds are angular rates (1.5 °/s and 12 °/s), so the behaviour does not depend on the output rate. If the dispersion inside the window exceeds 3 °/s·T (the phone is moving within the window), the most recent sample replaces the mean, because the mean would lag by half a period.
Code: core/smoother.cpp.
10. Orientation outputs
Euler angles, intrinsic sequence Z-Y′-X″ (yaw ψ measured counter-clockwise from East, pitch θ, roll φ), device → ENU [2, 3]:
Near θ = ±90° yaw and roll are not individually defined (gimbal lock); the quaternion is always valid and is shown alongside.
Compass heading of the top edge of the phone, clockwise from magnetic north; when the phone is almost vertical (the top edge less than ~17° from vertical) the direction of the rear camera, −z, is used instead:
The heading is magnetic. To obtain the geographic (true) heading add the local magnetic declination, which can be obtained from the NOAA calculator based on the World Magnetic Model [23, 24].
11. Angle in a plane
When “Set zero” is pressed, the current orientation is stored as qref. The relative rotation is decomposed into a twist about the device z axis (perpendicular to the screen) and a swing about an axis lying in the screen plane [13]:
γ is shown clockwise as seen from the screen, in [0°, 360°) and in (−180°, 180°]; s tells how far the phone has left the reference plane and should stay close to 0°. Because only the relative rotation matters, the measurement works on any surface — horizontal, inclined or vertical — and does not need the magnetometer. Over long periods it is limited by gyroscope drift; set the zero again for long sessions.
12. Level and plumb
The world vertical expressed in the device is the third row of R:
Flat (|uz| is the largest component): elevation of the right side (a), of the top edge (b) and total tilt:
On an edge (portrait or landscape): clockwise deviation from the nearest multiple of 90° (a) and lean of the screen out of the vertical, i.e. plumb (b):
The phone position is classified into six faces (screen up, screen down, two portrait and two landscape) by the largest component of u. The two linear levels show a (bottom tube) and b (side tube) on a compressed scale, so that hundredths of a degree and several degrees are visible on the same tube:
13. Calibration and reference
13.1 Reversal calibration
Every phone has a small accelerometer offset and a mounting misalignment between the sensor and the case, often 0.2°–1°. On the same spot, turning the phone 180° (with the same side down) changes the sign of the surface inclination s but not of the instrument error o — the classic reversal method used with precision spirit levels:
An offset (a, b) is stored for each of the six faces and saved on the phone. A reading is accepted only when the phone is still and σ < 0.05°.
13.2 User reference (differential level)
“Set reference” stores the calibrated reading (ar, br) and the face; while the phone stays on that face the level shows differences, and the total tilt is recomputed consistently:
The reference lives only in memory. The CSV record always contains both the differential and the absolute (calibrated) values.
14. Accuracy
The figures below are typical orders of magnitude for phone sensors; each device is different.
| Error source | Effect | What reduces it |
|---|---|---|
| Accelerometer white noise | ≈ 0.1° per sample | Window mean: ≈ 0.01–0.02° at 3 Hz; SLERP smoothing |
| Accelerometer offset and misalignment | 0.2°–1° on the level | Reversal calibration (section 13) |
| Linear acceleration (moving the phone) | Several degrees | Adaptive gain; read the values when “Stable” is shown |
| Gyroscope bias | Tilt error β·τa; drift of the plane angle | Bias estimate at rest; reset the zero in long sessions |
| Magnetic disturbances | Heading errors of several degrees | Disturbance detection; move away from metal; figure-8 calibration |
| Magnetic declination | Magnetic ≠ geographic north | Add the local declination [23] |
| Case and camera bump | The phone does not rest on its true faces | Remove the case; use the reference or the calibration |
The status line shows “Stable ±σ” with the dispersion of the last window: it is the best indicator of when a reading can be trusted.
15. CSV record
The scope mode records one row per output sample in a text file with comma separators and a decimal point [25]. The first row holds the variable names (with units); each row starts with a UTC timestamp in ISO 8601 with milliseconds [26] and the time since the first row, measured with the sensor clock, which is monotonic and does not jump if the system clock is adjusted.
| Columns | Meaning |
|---|---|
utc_time, t_s, sensor_time_s | UTC timestamp, seconds since the first row, sensor clock [s] |
qw, qx, qy, qz | Filtered quaternion, device → ENU |
yaw_deg, pitch_deg, roll_deg | Euler angles Z-Y′-X″ [°] |
heading_deg | Compass heading from magnetic north [°] |
plane_deg, plane_signed_deg, plane_swing_deg, plane_has_zero | Angle in the plane and its swing; 1 if a zero is set |
level_face, level_flat, level_a_deg, level_b_deg, level_total_deg | Face (0–5), flat (1) or edge (0), level values (differential when a reference is active) |
level_calibrated, cal_state, level_ref, level_a_abs_deg, level_b_abs_deg | Calibration and reference states; absolute calibrated level values |
rms_deg, still | Dispersion of the window [°]; 1 when the phone is still |
mag_status, mag_disturbed, use_mag | Magnetometer accuracy reported by Android (−1 to 3), disturbance flag, compass on/off |
gyro_hz, sensors | Measured gyroscope rate [Hz]; bit mask of available sensors (1 accelerometer, 2 gyroscope, 4 magnetometer) |
The file is written by the engine thread into the app cache and handed over once — saved with the system document picker or shared — and then deleted. The app keeps no history.
16. Implementation
- A dedicated native thread with its own
ALooperreads the sensor queue [21]; the interface never receives raw samples, it only reads a snapshot published at the output rate. - No memory is allocated in the sensor loop; all the mathematics is inline double-precision code. One update costs a few hundred floating-point operations.
- The core (
core/) does not depend on Android and is tested on a PC with synthetic data: noise, gyroscope bias, rotations, vibrations and magnetic disturbances (72 checks). - The engine is documented with Doxygen; this guide and the README describe how to add a new measurement.
Source code: https://github.com/carlosperezco/SuaGeometry. The formulas on this page are rendered with MathML [27].
17. References
Papers and books are cited by DOI where one exists; Android documentation by its official URL.
- Hamilton, W. R. (1844). On quaternions; or on a new system of imaginaries in algebra. Philosophical Magazine, Series 3, 25(163), 10–13. https://doi.org/10.1080/14786444408644923
- Shuster, M. D. (1993). A survey of attitude representations. The Journal of the Astronautical Sciences, 41(4), 439–517.
- Diebel, J. (2006). Representing Attitude: Euler Angles, Unit Quaternions, and Rotation Vectors. Technical report, Stanford University.
- Kuipers, J. B. (1999). Quaternions and Rotation Sequences. Princeton University Press.
- Markley, F. L., Crassidis, J. L. (2014). Fundamentals of Spacecraft Attitude Determination and Control. Springer. https://doi.org/10.1007/978-1-4939-0802-8
- Solà, J. (2017). Quaternion kinematics for the error-state Kalman filter. arXiv:1711.02508. https://arxiv.org/abs/1711.02508
- Shepperd, S. W. (1978). Quaternion from rotation matrix. Journal of Guidance and Control, 1(3), 223–224. https://doi.org/10.2514/3.55767b
- Mahony, R., Hamel, T., Pflimlin, J.-M. (2008). Nonlinear complementary filters on the special orthogonal group. IEEE Transactions on Automatic Control, 53(5), 1203–1218. https://doi.org/10.1109/TAC.2008.923738
- Madgwick, S. O. H., Harrison, A. J. L., Vaidyanathan, R. (2011). Estimation of IMU and MARG orientation using a gradient descent algorithm. IEEE International Conference on Rehabilitation Robotics (ICORR). https://doi.org/10.1109/ICORR.2011.5975346
- Valenti, R. G., Dryanovski, I., Xiao, J. (2015). Keeping a good attitude: a quaternion-based orientation filter for IMUs and MARGs. Sensors, 15(8), 19302–19330. https://doi.org/10.3390/s150819302
- Shoemake, K. (1985). Animating rotation with quaternion curves. ACM SIGGRAPH Computer Graphics, 19(3), 245–254. https://doi.org/10.1145/325165.325242
- Markley, F. L., Cheng, Y., Crassidis, J. L., Oshman, Y. (2007). Averaging quaternions. Journal of Guidance, Control, and Dynamics, 30(4), 1193–1197. https://doi.org/10.2514/1.28949
- Dobrowolski, P. (2015). Swing-twist decomposition in Clifford algebra. arXiv:1506.05481. https://arxiv.org/abs/1506.05481
- Hogenauer, E. B. (1981). An economical class of digital filters for decimation and interpolation. IEEE Transactions on Acoustics, Speech, and Signal Processing, 29(2), 155–162. https://doi.org/10.1109/TASSP.1981.1163535
- Oppenheim, A. V., Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson.
- Titterton, D. H., Weston, J. L. (2004). Strapdown Inertial Navigation Technology, 2nd ed. IET.
- Groves, P. D. (2013). Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd ed. Artech House.
- Android Developers. Sensors overview (sensor coordinate system). https://developer.android.com/develop/sensors-and-location/sensors/sensors_overview
- Android Developers. Motion sensors. https://developer.android.com/develop/sensors-and-location/sensors/sensors_motion
- Android Developers. Position sensors. https://developer.android.com/develop/sensors-and-location/sensors/sensors_position
- Android NDK API reference. Sensor (
<android/sensor.h>). https://developer.android.com/ndk/reference/group/sensor - Android Open Source Project. Sensor types. https://source.android.com/docs/core/interaction/sensors/sensor-types
- NOAA NCEI. Magnetic field calculators (declination). https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml
- NOAA NCEI / British Geological Survey. World Magnetic Model. https://www.ncei.noaa.gov/products/world-magnetic-model
- Shafranovich, Y. (2005). RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files. IETF. https://www.rfc-editor.org/rfc/rfc4180
- ISO 8601. Date and time format. https://www.iso.org/iso-8601-date-and-time-format.html
- W3C. MathML Core. https://www.w3.org/TR/mathml-core/