This library fuses the outputs of an inertial measurement unit (IMU) and stores the heading as a quaternion. It uses a kalman-like filter to check the acceleration and see if it lies within a deviation from (0,0,1)g. If the acceleration is within this band, it will strongly correct the orientation. However, if the acceleration lies outside of this band, it will barely affect the orientation. To this end, the deviation from vertical is used to update the variance and kalman gain:
$\ \overrightarrow{a{rel}} = \overrightarrow{a{local}} - (0,0,1) $
$\ K{\sigma} = 1/(1 + \frac{ {\sigma}^2 }{ {\sigma}{acc}^2 } ) $
$\ {\sigma}^2 = | \overrightarrow{a{rel}} |^2 + K{\sigma}{\sigma}^2 $
The kalman gain then scaled by a delay parameter and used to correct the attitude. This scaling allows the filter to act like a 1rst-order low pass filter that smoothens the acceleration at the cost of slower response:
$\ E{k} = \theta{accel} - \theta_{k-1} $
$\ K{\theta} = {\alpha} K{\sigma} {\Delta t} $
$\ \theta{k} = \theta{k-1} + \dot{\theta}{\Delta t} + K{\theta}E{k} $
As the filter uses a quaternion to encode rotations, it's easy to perform coordinate transformations. The library has functions to:
Moreover, since a 6-axis IMU (gyro-accelerometer) cannot measure an absolute heading, a function is included to rotate the orientation about the vertical (yaw) axis. One can use vector operations to correct the heading with an additional sensor like a magnetometer.
The library can integrate acceleration to obtain an estimate of velocity. This is accomplished by using a set of Kalman-like filters like the one shown above. The acceleration is checked against a rest condition of (0,0,0)g and any deviations that lie within a specified uncertainty band are suppressed. This eliminates much of the bias due to gravity or miscalibration:
$\ K{acc} = 1/(1 + \frac{ S{acc}^2 }{ {\sigma}_{acc}^2 } ) $
$\ S{acc}^2 = | \overrightarrow{a{rel}} |^2 + K{acc}S{acc}^2 $
$\ a{k} = a{k} - \overline{a_{k}} $
$\ \overline{a{k}} = \overline{a{k-1}} + K{acc}{a{k}} $
Afterward, the deviation of the velocity (relative to a known target velocity), along with the variance of the acceleration, is used to determine the Kalman gain of the velocity. This relationship causes small velocity changes or small accelerations to reduce the gain, and the velocity is forced to match the target velocity:
$\ \Delta{V} = V{k-1} - V{target} $
$\ S{vel}^2 = | \overrightarrow{ {\Delta}V } |^2 + K{vel}S_{vel}^2 $
$\ K{vel} = 1/(1 + ( \frac{ S{vel} S{acc} }{ \sigma{vel} \sigma_{acc} } )^2 ) $
The velocity is then updated using the trapezoidal rule to integrate the filtered acceleration:
$\ V{k} = V{k-1} + K{vel}{\Delta}{V} + \frac{dt}{2}( a{k} + a_{k-1} ) $
This library depends on the vector_datatype library.
The form of the filter is inspired by the SimpleKalmanFilter library.