Many embedded systems need to track their own location or position and heading, and designers often turn to GNSS (Global Navigation Satellite Systems) as a first resort (see, “Design Location Tracking Systems Quickly Using GNSS Modules”). However, GPS cannot always be used exclusively for position and heading information for several reasons, starting with power consumption.

GPS systems draw significant amounts of power. Many embedded systems, especially battery powered, cannot afford the power budget needed to maintain a GPS position 100 percent of the time. In addition, GPSs suffer from signal blockages, slow update rates, and an accuracy of 1 meter (m) that might not be sufficient for some applications.

These problems can be overcome by using inertial measurement units (IMUs) to complement GNSS position data.

A previous IMU article discussed the use of relatively inexpensive IMUs based on MEMs technology for determining position and heading, see “Use IMUs for Precise Location Data When GPS Won’t Suffice”. However, IMU sensor data alone cannot provide absolute position. While GNSS receivers simply provide location data, a significant amount of software is required to convert an IMU’s relative motion data into an absolute position and heading using sensor filtering, fusion, and double integration.

This article discusses the embedded use of IMUs, sources of error in the data from various IMU sensors, and the software needed to calculate precise location and heading information from IMU sensors. In addition, this article discusses the STMicroelectronics MotionFX library and how to use this software to transform IMU sensor data into position and heading within an embedded system.

## How IMUs complement GNSS receivers

The problems with GNSS are fourfold:

- GNSS signals are very directional and are easily blocked by buildings. Therefore, GNSS operation indoors or deep within urban concrete canyons can be problematic.
- GNSS receivers have warm and cold startup times measured in the tens of seconds or more. If the GNSS receiver is not operated continuously, to save energy for example, then each new position reading can take multiple seconds.
- GNSS’ position update rate is limited to once per second. This update rate is not sufficiently frequent for embedded applications involving quick movement. There’s a long list of such applications ranging from virtual reality to materials handling and robotics.
- GNSS accuracy is measured in meters. That resolution is far too coarse for use in many embedded applications.

IMUs provide the finer positioning resolution and faster update rates that are required by many embedded applications. Also, IMUs provide relative position data from a known starting point as opposed to the absolute positioning information from a GNSS receiver, so the two types of position sensors complement each other. These IMU characteristics make them quite useful for augmenting the positioning information obtained directly from GNSS receivers, see “Design Location Tracking Systems Quickly Using GNSS Modules”.

IMUs have existed in the aerospace industry for many decades. However, these precision aerospace IMUs are based on expensive gyroscopes and other large sensors, and are difficult to apply to more cost-sensitive systems.

Modern electronic IMUs are highly integrated and can contain a mix of sensor types—accelerometers, gyroscopes, and magnetometers—which are based on microelectromechanical systems (MEMS) technology so they’re small, light, and relatively rugged. These new generations of IMUs are available as board mountable components and are proving to be ideal for embedded applications.

IMUs come with varying capabilities in terms of degrees of freedom (DOF), and unlike GNSS receivers, IMUs do not depend upon radio signals for position data. They also consume very little power and they’re available from a variety of sources with a wide range of resolution and accuracy specifications.

With these characteristics, IMUs can be used to augment positioning information from GNSS receiver modules (see, “Design Location Tracking Systems Quickly Using GNSS Modules”), but not without a significant amount of software to filter the IMU sensor data, to fuse sensor data from the several types of sensors inside the IMU, and to calculate a position from that fused sensor data using double integration.

## Sources of IMU error

Combining sensors to improve accuracy has long been a common practice in the aerospace industry, where accelerometers and gyroscopes are extensively used in inertial navigation systems. In these systems, gyroscopes sense orientation through angular velocity changes, but they tend to drift over time because they only sense changes and have no fixed frame of reference. Adding accelerometer data to the gyroscope data allows the gyroscope bias to be minimized, resulting in a more accurate location estimate. Accelerometers sense changes in direction with respect to gravity, and that data can be used to orient a gyroscope.

Accelerometers are more accurate for static (as opposed to dynamic) calculations. Gyroscopes are better at detecting orientation when the system is already in motion. Accelerometers react quickly, so accelerometer jitter and noise produce accumulated error when that data is used alone. In addition, accelerometers tend to distort accelerations due to external forces such as gravitational forces, which also accumulate in the system as noise.

Combining a gyroscope’s long-term accuracy with an accelerometer’s short-term accuracy results in more precise orientation readings by relying on each sensor’s strengths to cancel or at least reduce the other sensor’s weaknesses. The two sensor types complement each other.

## Fused filtering needed to reduce error

IMU software uses filtering to minimize positioning error from IMU data. Several filtering methods for fusing sensor data are available, each with varying degrees of complexity. A complementary filter is a simple way to combine data from several sensors. Complementary filtering is a linear function that combines a high pass gyroscope filter and low pass accelerometer filter. High frequency noise in the accelerometer data is therefore filtered out in the short term and smoothed by the gyroscope data.

While the complementary filter is computationally simple, more involved techniques such as the Kalman filter are now preferred for IMU use to achieve better accuracy. The Kalman filter is a very popular recursive sensor fusion algorithm because it does not take a lot of processing power to create a more accurate positioning system. There are different types of Kalman filtering including the standard Kalman filter, the extended Kalman filter (EKF) and the unscented Kalman filter (UKF).

A Kalman filter predicts values using several mathematical equations based on the assumption that the data being filtered takes the form of a Gaussian distribution, to which the filter applies linear equations. However, motion in the real world is not as clean as the Kalman filter’s assumption. Real-world motion adheres to equations often involving sine and cosine functions which are nonlinear, so the EKF employs a Taylor series and single point approximations of the Gaussian distribution to linearize nonlinear functions. These approximations can be significant error sources.

The UKF addresses this error problem by using a deterministic sampling approach that generates a set of carefully chosen sample points to represent expected Gaussian distribution of the data rather than the single approximation used by the EKF. These sample points completely capture the true mean and covariance of the expected Gaussian values and result in more accurate filtering.

## Magnetometer error sources

A typical IMU contains three different sensors: a gyroscope to measure angular rate/velocity, an accelerometer to measure linear acceleration, and a magnetometer to measure magnetic field strength. More specifically, the IMU’s magnetometers measure the earth’s magnetic field strength to determine a heading relative to the earth’s magnetic north. An IMU designed for navigation applications will usually contain three of each type of sensor, to cover the three orthogonal motion axes.

However, magnetometers are susceptible to hard iron and soft iron distortions. Distortions of the earth's magnetic field that result from external magnetic influences are generally classified as either a hard iron or soft iron effect. If no distorting effects are present, rotating a magnetometer through 360° and plotting the resulting data will result in data that forms a circle centered around (0, 0) (Figure 1).

*Figure 1: Rotating a magnetometer through 360° and plotting the resulting data will result in data that forms a circle centered on location (0, 0), if there are no local field distortions caused by nearby iron. (Image source: sensorsmag.com)*

The presence of hard iron and/or soft iron effects may disturb the circle. Hard iron effects cause a simple offset from location (0, 0) (Figure 2).

*Figure 2: A hard iron distortion effect offsets the magnetic data from location (0, 0). (Image source: sensorsmag.com)*

Soft iron effects deform the circle to produce an ellipse (Figure 3).

*Figure 3: A soft iron distortion effect distorts the 360° magnetic data, changing it from a circle into an ellipse. (Image source: sensorsmag.com)*

Note that both hard and soft iron effects can appear simultaneously.

The calculations that compensate for soft iron distortion are more compute intensive than those required to compensate for hard iron distortion, so it may be more efficient and cost effective simply to move soft iron materials away from the IMU’s magnetometers. However, in many cases this is not an option and compensation calculations will be required.

## Integrate, then integrate again

Finally, because the accelerometers and gyroscopes only provide information about the acceleration forces (linear and rotary) on an object, that data must be integrated twice to produce location because acceleration is the rate of change of an object’s velocity, and velocity is the rate of change of an object’s position. In other words, IMU gyroscope and accelerometer data provide the double derivatives of an object’s absolute location.

Double integration alone requires a fair bit of processing, but for 3D positioning the acceleration effects of gravity must be nulled out as well. Gravity looks like a constant acceleration to an accelerometer, resulting in an offset in its data. Usually, the acceleration effects of gravity must be calibrated out of the system while the IMU and the object containing the IMU are at rest.

Note that there will be errors caused by this double integration due to sampling error. The slower the sample rate, the greater the error.

## Design considerations for IMU software

Consider the following steps and recommendations when implementing these kinds of algorithms for real-world IMU software:

- IMU sensor signals are not free of noise and will require digital filtering. Typically, some sort of Kalman filtering is used in IMU applications.
- Even with filtering, additional error sources will be present such as mechanical noise coupled to the IMU, and the hard iron and soft iron distortion discussed above. This noise must be filtered out or otherwise removed from the data.
- A calibration routine performed while the IMU is at rest will be required at the start of the application because to be as accurate as possible, the software will need to know what the sensor readings are when the object is not moving. The real acceleration value for an object in motion is the current sample from an acceleration sensor minus the calibration value.
- After calibration, sensor values can be either positive or negative. Therefore, variables to hold these values must be signed.
- A faster sampling frequency for the sensor data produces more accurate results, but more samples will require more memory, tighter timing requirements, and perhaps other hardware considerations.
- The sampling period must always be precisely the same. Unequal sample periods will cause data errors.
- Linear data approximation between samples (interpolation) produces more accurate results but also requires more processing time.

From the above discussion, it’s apparent that the calculations needed to determine heading, position, and motion from IMU data are not simple. For that reason, IMU vendors often offer software application packages to perform these calculations for their products. For example, STMicroelectronics has developed the MotionFX library which expands the capabilities of the company’s downloadable X-CUBE-MEMS1 software to encompass IMU functions.

Software in this library acquires data from the accelerometers, gyroscopes, and magnetometers and provides real-time motion sensor data fusion for STMicroelectronics' MEMS sensors, including IMUs. The MotionFX filtering and predictive software uses advanced algorithms to intelligently integrate outputs from multiple MEMS sensors, regardless of environmental conditions. This library is only designed for STMicroelectronics’ MEMS IMUs so the software’s functionality and performance are not assured when using IMUs from other vendors.

The MotionFX library runs on a variety of STMicroelectronics’ microcontrollers based on the Arm® Cortex®-M0+, Cortex-M3, and Cortex-M4 processor cores. Sample implementations are available for the STMicroelectronics X-NUCLEO-IKS01A2 expansion board (Figure 4), when mounted on:

- the NUCLEO-F401RE development board based on an STM32F4 MCU, which incorporates an Arm Cortex-M4 processor core,
- the NUCLEO-L476RG development board based on an STM32L4 MCU, which incorporates an Arm Cortex-M4 processor core,
- the NUCLEO-L152RE development board based on an STM32L1 MCU, which incorporates an Arm Cortex-M3 processor core,
- ·or the NUCLEO-L073RZ development board based on an STM32L0 MCU, which incorporates an Arm Cortex-M0+ processor core.

STMicroelectronics’ MotionFX library manages and fuses the data acquired from an IMU’s accelerometers, gyroscopes, and magnetometers. The library provides routines for:

- Real time, 9-axis, motion sensor data fusion (accelerometer, gyroscope, magnetometer)
- Real time, 6-axis, motion sensor data fusion (accelerometer, gyroscope)
- Computation of rotation, quaternions, gravity, and linear acceleration data
- Gyroscope bias calibration
- Magnetometer hard iron calibration

STMicroelectronics recommends a 100 Hz sensor data sampling frequency when using MotionFX software.

*Figure 4: STMicroelectronics’ X-NUCLEO-IKS01A2 expansion board is supported by the company’s MotionFX software for IMUs. (Image source: STMicroelectronics)*

The MotionFX library implements a sensor fusion algorithm for the estimation of 3D orientation in space. It filters and fuses data from several sensors to compensate for the limitations of the IMU’s individual sensors.

Listing 1 provides demo code that shows what is needed to get the STMicroelectronics IMU up and running.

`Copy````
[…]
#define VERSION_STR_LENG 35
#define MFX_DELTATIME 10
[…]
/*** Initialization ***/
char lib_version[VERSION_STR_LENG];
char acc_orientation[3];
MFX_knobs_t iKnobs;
/* Sensor Fusion API initialization function */
MotionFX_initialize();
/* Optional: Get version */
MotionFX_GetLibVersion(lib_version);
MotionFX_getKnobs(&iKnobs);
/* Modify knobs settings */
MotionFX_setKnobs(&iKnobs);
/* Enable 9-axis sensor fusion */
MotionFX_enable_9X(MFX_ENGINE_ENABLE);
[…]
/*** Using Sensor Fusion algorithm ***/
Timer_OR_DataRate_Interrupt_Handler()
{
MFX_input_t data_in;
MFX_output_t data_out;
/* Get acceleration X/Y/Z in g */
MEMS_Read_AccValue(data_in.acc[0], data_in.acc[1], data_in.acc[2]);
/* Get angular rate X/Y/Z in dps */
MEMS_Read_GyroValue(data_in.gyro[0], data_in.gyro[1], data_in.gyro[2]);
/* Get magnetic field X/Y/Z in uT/50 */
MEMS_Read_MagValue(data_in.mag[0], data_in.mag[1], &data_in.mag[2]);
/* Run Sensor Fusion algorithm */
MotionFX_propagate(&data_out, &data_in, MFX_DELTATIME);
MotionFX_update(&data_out, &data_in, MFX_DELTATIME, NULL);
}
```

*Listing 1: Demo code shows use of the MotionFX library for extracting information from the IMU components on the company’s X-NUCLEO-IKS01A2 expansion board. (Code source: STMicroelectronics)*

A flowchart of the demo software is also shown (Figure 5).

*Figure 5: This flowchart illustrates the sequence of steps used by the MotionFX demo code in Listing 1 to extract data from STMicroelectronics’ X-NUCLEO-IKS01A2 expansion board and fuse it into a 3D spatial orientation. (Image source: STMicroelectronics)*

Note that gyroscope data can drift, which can degrade the estimation of 3D spatial orientation. The MotionFX software can compensate for this degradation by using magnetometer data, which provides absolute orientation information. At the same time, magnetometers do not produce heading data at high rates and they suffer from magnetic disturbances, but gyroscope data can compensate for these magnetometer weaknesses.

The MotionFX software’s 9-axis sensor fusion calculations use data from the accelerometer, gyroscope, and magnetometer to provide absolute orientation in 3D space, including heading (relative to magnetic north).

The MotionFX software’s 6-axis sensor fusion calculations only use accelerometer and gyroscope data. This operational level has lower computational requirements and does not provide information about absolute orientation, but the routines run faster than the 9-axis routines. 6-axis sensor fusion is suitable for measuring fast movements, such as for gaming or for stationary robots, and can also be used when absolute orientation is not necessary.

## Conclusion

IMUs are quite useful in embedded applications for providing location and heading information by themselves. They are also useful when used to augment GNSS receiver information when even higher precision or faster update rates are required. However, incorporating an IMU into an embedded system requires a significant amount of software, which IMU providers frequently supply to aid in the real-world application of these devices.