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

ampheoampheo
2 min read

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.


SensorFeaturesInterfaceNotes
MPU60503-axis gyro + 3-axis accelerometerI2CWidely used, basic IMU
MPU9250MPU6050 + 3-axis magnetometerI2C/SPI9-DOF IMU
ICM209489-axis IMU, lower powerI2C/SPISuccessor to MPU9250
LSM6DS36-axis (gyro + accel)I2C/SPIFrom STMicroelectronics
BMI1606-axis, low-power motion sensorI2C/SPIHigh performance, low power
BNO0559-axis with onboard fusionI2CNo 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.

0
Subscribe to my newsletter

Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ampheo
ampheo