How to interface various IMU sensors with STM32 via I2C or SPI?


Using IMU sensors (Inertial Measurement Units) with STM32 microcontrollers is a common practice in robotics, drones, motion tracking, and navigation systems. Here’s a practical guide on interfacing various IMU sensors with STM32 via I2C or SPI, and how to process their data.
Popular IMU Sensors and Interfaces
Sensor | Features | Interface | Notes |
MPU6050 | 3-axis gyro + 3-axis accelerometer | I2C | Widely used, basic IMU |
MPU9250 | MPU6050 + 3-axis magnetometer | I2C/SPI | 9-DOF IMU |
ICM20948 | 9-axis IMU, lower power | I2C/SPI | Successor to MPU9250 |
LSM6DS3 | 6-axis (gyro + accel) | I2C/SPI | From STMicroelectronics |
BMI160 | 6-axis, low-power motion sensor | I2C/SPI | High performance, low power |
BNO055 | 9-axis with onboard fusion | I2C | No need for external algorithm |
Steps to Interface IMU with STM32
1. Hardware Setup
Connect SCL/SDA (for I2C) or SCK/MISO/MOSI/CS (for SPI) to STM32 pins.
Use pull-up resistors (4.7kΩ typical) for I2C.
Power with 3.3V (check datasheet!).
2. STM32CubeMX Configuration
Enable I2C1 or SPI1 in CubeMX.
Set appropriate GPIOs for communication.
Generate code using HAL drivers.
3. Reading Data (Example: MPU6050 via I2C)
c
#define MPU6050_ADDR (0x68 << 1)
#define WHO_AM_I 0x75
#define ACCEL_XOUT_H 0x3B
uint8_t check, data[14];
// Check device ID
HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, WHO_AM_I, 1, &check, 1, HAL_MAX_DELAY);
// Read raw accel and gyro data
HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, ACCEL_XOUT_H, 1, data, 14, HAL_MAX_DELAY);
int16_t ax = (data[0] << 8) | data[1];
int16_t ay = (data[2] << 8) | data[3];
int16_t az = (data[4] << 8) | data[5];
4. Data Conversion
Each IMU has a sensitivity scale. Example for MPU6050:
c
float accelX = ax / 16384.0; // if FS = ±2g
float gyroX = gx / 131.0; // if FS = ±250 °/s
5. Sensor Fusion (Optional)
To combine accelerometer, gyroscope, and magnetometer data into orientation angles, use:
Complementary Filter (simple, fast)
Kalman Filter (complex, accurate)
Madgwick/Mahony algorithms (open source)
Tips
Use interrupts for real-time motion detection.
For accurate angles, integrate gyro data and correct drift with accelerometer/magnetometer.
Consider RTOS (FreeRTOS) for multitasking sensor reads and processing.
Driver Options
Use ready-made libraries (e.g., from ST, Bosch, or Arduino ported drivers).
Or write a custom driver by reading sensor datasheets and using HAL functions.
Subscribe to my newsletter
Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
