--- title: Madgwick Filter created_date: 2025-06-30 updated_date: 2025-06-30 aliases: tags: --- # Madgwick Filter ## Summary - All operations are being done in [[Quaternion]]s for smooth and continuous rotation operations as well as to avoid the gimbal lock - [[Accelerometer]], [[Gyroscope]] and [[Magnetometer]]s are used as the input in order to estimate the attitude. - The [[Gradient Descent]] Method is used, in order to minimize the error between the measured and the estimated gravity and magnetic field vectors. This error is expressed as a cost function $J(q)$ - The angular velocity data from the gyroscope is used to update the attitude quaternion by integrating it: $\dot{q}=\frac{1}{2}q\times \omega$ - The accelerometer and magnetometer data are used to correct the drift in the gyroscope's integration. The correction is based on the expected vs the measured direction of gravity and the magnetic north. - The filter uses a complementary filter type to combine the different sensor types. This ensures the short-term (high frequency) changes are guided by the gyroscope and the long-term (low frequency) orientation is corrected by the accelerometer and the magnetometer. - we always normalize the quaternion to maintain a unit quaternion. ## Detailed Analysis White Paper: ![[madgwick_internal_report.pdf]] And official implementation: [Fusion/Fusion/FusionOffset.c at main · xioTechnologies/Fusion · GitHub](https://github.com/xioTechnologies/Fusion/blob/main/Fusion/FusionOffset.c) Quaternion rotation $$ {}^{B}\mathbf{v} \;=\; {}^{A}_{B}\hat{\mathbf{q}} \;\otimes\; {}^{A}\mathbf{v} \;\otimes\; {}^{A}_{B}\hat{\mathbf{q}}^{*} $$ ### Filter Derivation Definitions. - $S$: Sensor Frame - $E$: Earth Frame The Gyroscope measures: $\omega_x$, $\omega_y$, $\omega_z$ in $rads^{-1}$ This means we can define the following vector (format used to rotate it with a quaternion): $${}^{S}\boldsymbol{\omega}= \begin{bmatrix} 0 & \omega_x & \omega_y & \omega_z \end{bmatrix}$$ ## Comparison agains the [[Kalman Filter]] 1. Madgwick's algorithm is computationally more efficient. It's simpler and requires fewer computations. 2. The Madgwick's algorithm is simpler and more straightforward to implement. 3. The Madgwick's algorithm does require minimal tuning compared to the Kalman filter 4. Madgwick's algorithm can have bettter robustness to sensor noise ## Resources - [Original White Paper - 2010](https://x-io.co.uk/downloads/madgwick_internal_report.pdf) -