STM32-Based IMU Attitude Estimation

From PC5271 wiki
Revision as of 19:53, 6 April 2025 by Liding (talk | contribs) (Equipment)
Jump to navigationJump to search

This project involves using an STM32 microcontroller and an MPU6050 sensor module to measure angular velocity and acceleration. The collected sensor data will be processed to determine the attitude angles (roll, pitch, and yaw) of the system. The project will include sensor calibration, data filtering (e.g., complementary or Kalman filter), and real-time angle computation for accurate motion tracking applications.


Introduction

In this project, we built a simple attitude estimation system using the STM32F103C8T6 microcontroller and the MPU6050 inertial measurement unit (IMU). The MPU6050 contains a 3-axis accelerometer and a 3-axis gyroscope, which together allow us to sense both linear acceleration and angular velocity in space.

Our goal was to estimate the orientation of the sensor in real time—specifically the roll, pitch, and yaw angles—by processing the raw physical signals output by the sensor. The core idea is based on how physical forces like gravity and rotational motion affect the internal elements of MEMS sensors, and how these effects can be digitized and interpreted.

To make the system work, we wrote low-level I²C communication routines to read data directly from the MPU6050 registers. The raw measurements were then converted into meaningful physical quantities, and passed into a complementary filter, which combines accelerometer and gyroscope data to produce smoother and more stable angle estimates.

The main steps of the project include:

  • Reading raw acceleration and gyroscope data via I²C
  • Calibrating the sensor to reduce offset and random noise
  • Computing roll and pitch using a complementary filter
  • Updating and displaying the estimated angles in real time on an OLED screen

Although this system is relatively simple, it closely reflects the principles used in real-world applications like drone stabilization, smartphone orientation sensing, and robot balancing. More importantly, it helps us explore how sensor physics—particularly the detection of inertial forces—can be harnessed in embedded systems to measure motion and orientation.

Team Members

LI DING

FAN XUTING

Project Overview

The core idea of this project is to estimate the orientation (attitude) of an object in space using inertial sensor data. We used the MPU6050 module, which integrates a 3-axis accelerometer and a 3-axis gyroscope, to measure two different physical quantities: linear acceleration and angular velocity. These are fundamental mechanical observables when analyzing motion.

The data from the sensor is acquired through I²C communication using the STM32F103C8T6 microcontroller. However, the raw measurements—especially from the gyroscope—tend to drift over time, and the accelerometer is sensitive to external vibrations. Therefore, we applied a complementary filter to combine the short-term precision of the gyroscope with the long-term stability of the accelerometer. This approach helps us reduce noise and improve the reliability of the estimated angles.

Our objective is to continuously compute the roll, pitch, and yaw angles of the sensor in real time. In practice, only roll and pitch can be estimated reliably without a magnetometer, since yaw depends on integrating rotational velocity around the vertical axis and is subject to drift.

Systems like this are commonly found in drones, balancing robots, camera gimbals, and even smartphones for orientation detection. In our project, we replicated the basic functionality of such systems on a smaller scale in order to understand how physical quantities—like gravity and rotation—can be sensed, processed, and interpreted through embedded electronics.

Setup

Equipment

The following components were used to build our attitude estimation system:

  • **STM32F103C8T6 ("Blue Pill")** – A low-cost 32-bit microcontroller used here to handle I²C communication, filtering, and OLED output.
  • **MPU6050** – A 6-axis IMU that combines a 3-axis accelerometer (for sensing gravity and linear motion) and a 3-axis gyroscope (for measuring angular velocity).
  • **USB to TTL Serial Converter** – Used mainly during development to upload programs to the STM32 and read data from the serial port.
  • **Breadboard and jumper wires** – For making temporary connections during prototyping.
  • **3.3V Power Supply** – The MPU6050 operates at 3.3V, which is provided by the STM32 board itself.

The MPU6050 is connected to the STM32 using the I²C protocol. I²C is widely used in sensor interfacing due to its simplicity and ability to handle multiple devices over just two lines (SDA and SCL).

STM32F103C8T6 "Blue Pill" development board

Wiring / Circuit Overview

Here's how the components are connected:

MPU6050 Pin STM32 Pin Notes
VCC 3.3V Powered by STM32
GND GND Common ground
SDA PB7 I2C data line
SCL PB6 I2C clock line

The sensor is connected to the STM32 using the I2C interface, which allows the STM32 to read the sensor's data. I2C is a simple and efficient communication protocol for embedded systems.

Optional: A USB to TTL converter is used for programming the STM32 and debugging through the serial port. This allows us to print the sensor data or estimated angles to the terminal.

imu_wiring_diagram
Schematic diagram of electrical connections

Software & Code

All the software for this project was written in C, using STM32's standard peripheral libraries. The key steps in the code are:

  • **Initialize I2C communication** – Set up the I2C peripheral on the STM32 and ensure it can communicate with the MPU6050.
  • **Configure the MPU6050** – Set the sensor’s output scale, enable the gyroscope and accelerometer, and set the operating mode.
  • **Read raw data** – Read sensor registers over I2C (accelerometer in g, gyroscope in °/s).
  • **Convert raw values** – Convert to physical units like acceleration (g) and angular velocity (°/s).
  • **Estimate angles** – Use a complementary filter to fuse data, compute roll and pitch.
  • **Output results** – Print the final angles over serial for easy monitoring.

The code runs in a continuous loop, updating at a fixed interval (e.g., every 10ms) for smooth, real-time performance.

Theory & Angle Estimation

To estimate the orientation (attitude) of an object using the MPU6050 sensor, we need to understand both the physical meaning of the sensor outputs and how they can be processed to obtain rotation angles.

Sensor Principles

The MPU6050 is a 6-axis MEMS-based Inertial Measurement Unit (IMU). It consists of:

A 3-axis accelerometer – measures linear acceleration in x, y, z directions (in units of g)

A 3-axis gyroscope – measures angular velocity around x, y, z axes (in °/s)

These sensors give raw physical measurements:

The accelerometer reflects the direction of gravity and motion

The gyroscope measures how fast the object rotates

By analyzing both, we can estimate the orientation (roll, pitch, yaw) of the object.

MPU6050 module (breakout board), showing chip and I2C pins

Attitude Angles: Roll, Pitch, Yaw

Attitude refers to the rotation of an object in 3D space. It is commonly expressed using three angles:

Angle Axis Description Roll X-axis Tilting side-to-side Pitch Y-axis Tilting forward/backward Yaw Z-axis Rotating left/right In this project, we mainly estimate roll and pitch. Yaw is harder to determine accurately without a magnetometer.

Illustration of roll (X-axis), pitch (Y-axis), and yaw (Z-axis) in a 3D coordinate system.

Using the Accelerometer

When the object is still or moving slowly, the accelerometer can be used to estimate roll and pitch based on the gravity vector. The equations are:

pitch=arctan(axay2+az2) roll=arctan(ayax2+az2) These formulas give a rough estimate of the angle, but are sensitive to motion and vibration, which cause noise.

Using the Gyroscope

The gyroscope provides angular velocity. We can integrate this value over time to get angle changes: θ=θprev+ωΔt. However, small measurement errors accumulate over time, causing drift.

Complementary Filter

To overcome the weaknesses of both sensors, we use a complementary filter, which combines:

The short-term precision of the gyroscope

The long-term stability of the accelerometer

The formula is: θ=α(θprev+ωΔt)+(1α)θacc. Where: 𝜔 is angular velocity (from gyroscope), 𝜃 is the angle from the accelerometer, 𝛼 is a constant (typically 0.95 ~ 0.98).

This filter gives a smooth and responsive estimation of the roll and pitch angles.


Results

After completing the sensor initialization, calibration, and complementary filter implementation, we tested our system by manually changing the orientation of the MPU6050 module and observing the real-time calculated attitude angles: pitch, roll, and yaw. These values were displayed on the OLED screen in real time.

Initial State

In the initial state, the sensor was placed flat and stationary on the table. The calculated angles were close to zero, fluctuating slightly within ±1° due to sensor noise and environmental vibration.

Initial state: pitch ≈ 0°, roll ≈ 0°, yaw ≈ 0° (flat and stable).

Pitch Variation

We manually tilted the sensor forward and backward around the Y-axis to generate positive and negative pitch angles.

Pitch ≈ +45°
Pitch ≈ -45°

The pitch angle responded clearly and symmetrically to changes in tilt. The results remained stable when holding the angle.

Roll Variation

Next, we tilted the sensor side-to-side around the X-axis to test roll estimation.

Roll ≈ +45°
Roll ≈ -45°

The roll angle also showed accurate and consistent results. There was some fluctuation due to hand-held movement, but the trend was clear and repeatable.

Yaw Rotation

Since our yaw angle is calculated by integrating the Z-axis angular velocity, it is expected to drift over time. However, for short-term motion, it could still reflect relative rotation. We rotated the device on a flat surface and observed the change.

Yaw ≈ 0°
Yaw ≈ 90°

The yaw angle changed appropriately during rotation. However, due to the lack of a magnetometer, long-term drift is still present and was not corrected in our system.

Summary

The table below summarizes the approximate angles observed during different manual movements. The "Reference" column represents rough estimates of the sensor orientation based on intuition and relative movement, not exact measured angles.

Test Condition Estimated Tilt Measured Angle (OLED) Observation
Flat (Initial) ≈ 0° 0° ± 1° Stable near zero
Pitch Forward ~ +45° +46° Correct trend
Pitch Backward ~ -45° -46° Correct trend
Roll Right ~ +45° +46° Correct trend
Roll Left ~ -45° -48° Correct trend
Yaw No Rotation ~ 0° As expected
Yaw Rotated Clockwise ~ +90° +91° Matches rotation


Note: The reference angles were estimated by eye during manual movement. No precise angle measurement tools were used.

Pitch and roll estimation was stable and consistent throughout the tests. The angle values responded smoothly to manual tilting and aligned well with expected trends within an approximate ±45° range.

Yaw angle changes were visible and directionally accurate during short-term rotation, but drifted over time due to the lack of a magnetometer for correction.

All three angles were displayed clearly on the OLED screen and updated in real time at approximately 100 Hz.

Overall, the complementary filter worked effectively for basic attitude estimation using only the MPU6050 sensor, especially for roll and pitch. The system demonstrates reliable performance for short-term orientation tracking without external reference.

7. Discussion

Accuracy and Stability of Roll and Pitch

The complementary filter performed well in estimating roll and pitch angles. These two values remained stable when the sensor was held still, and they responded consistently to manual tilting. The accelerometer provides reliable long-term reference based on gravity, while the gyroscope helps improve short-term responsiveness. Minor fluctuations were observed due to hand tremors and environmental vibrations, but they were within acceptable range for basic applications.

Yaw Angle Limitations

Unlike pitch and roll, yaw cannot be derived from the accelerometer alone. In this project, yaw was computed by integrating gyroscope data around the Z-axis. This approach worked for short-term motion but exhibited noticeable drift over time, as expected. Without a magnetometer to provide an external reference (e.g., Earth's magnetic field), yaw estimation lacks long-term accuracy. This is a known limitation of using MPU6050 without additional sensors.

Display and Refresh Rate

Displaying angles on the OLED screen in real time (~100 Hz) allowed for intuitive observation of system performance. However, the OLED display has limited resolution and update speed compared to serial terminals or PC-based plots. Some rapid changes may not be fully captured visually.

Potential Improvements

To further improve the system:

  • A **magnetometer** (e.g., HMC5883L) can be added to correct yaw drift.
  • **Kalman filter** or **Madgwick filter** could replace the complementary filter for higher accuracy.
  • **Initial calibration** routines can be added to correct zero-bias errors in accelerometer and gyroscope.
  • Angle output could also be sent to PC or mobile app via serial/Bluetooth for better visualization.

Applications and Extensions

This basic attitude estimation system could be extended for use in:

  • Drone orientation feedback
  • Self-balancing robots
  • Gesture-based control systems
  • VR/AR head tracking

The understanding gained from building this project from scratch—both in hardware wiring and software logic—provides a strong foundation for further exploration in embedded sensing systems.

References

  • [1] **MPU6050 Register Map and Datasheet**, InvenSense.
   https://invensense.tdk.com/products/motion-tracking/6-axis/mpu-6050/
  • [2] **STM32F103C8T6 Datasheet**, STMicroelectronics.
   https://www.st.com/en/microcontrollers-microprocessors/stm32f103c8.html