11. Nine-axis attitude sensor to obtain data

11.1. Experimental purpose

Use the GPIO port of STM32 to simulate IIC communication, read the raw data of the nine-axis attitude sensor MPU9250, and print it out through the serial port assistant.

11.2. Configuration pin information

  1. Import the ioc file from the Serial project and name it Read_IMU.

According to the schematic diagram, the SDA/SDI pin of the nine-axis attitude sensor is connected to PB15, the SCL/SCLK pin is connected to PB13, and the AD0/SDO pin is connected to PB14.

image-20220326160652511

image-20220326160924577

  1. Set PB13, PB14 and PB15 as output mode, the specific parameters are as shown in the figure below:

image-20220326161827683

image-20220326161943690

11.3. Analysis of the experimental flow chart

image-20220519104232485

11.4. core code explanation

  1. Create new bsp_mpuiic.h and bsp_mpuiic.c, and add the following content to bsp_mpuiic.h:

image-20220326164305850

  1. Create the following content in the bsp_mpuiic.c file:

According to the content of the IIC protocol, MPU_IIC_Start() generates the IIC start signal, and MPU_IIC_Stop() generates the IIC stop signal.

image-20220326165916278

3.IIC response correlation function.

image-20220326165958615

4.IIC send and read data related functions.

image-20220326170033653

  1. Create new bsp_mpu9250.h and bsp_mpu9250.c, and add the following content to bsp_mpu9250.h:

image-20220326170429647

  1. Add the following related functions in bsp_mpu9250.c.

Pull the AD0 pin low to make the ID of the MPU6500 0x68.

image-20220326170244648

Initialize MPU9250, return value: 0, success, other, error code

image-20220326171949053

Read the gyroscope value (original value), return value: 0, success, other, error code

image-20220326170953477

Read acceleration value (original value), return value: 0, success, other, error code

image-20220326171021672

Read magnetometer value (raw value), return value: 0, success, other, error code

image-20220326171104396

Read and print data, called every 10ms.

image-20220326171144302

  1. Add the content of initializing MPU9250 in the Bsp_Init() function, if the initialization fails, stop the program.

image-20220326171240538

  1. Add the function of reading MPU9250 data in the Bsp_Loop() function.

image-20220326171349017

11.5. Hardware connection

The MPU9250 nine-axis attitude sensor has been soldered on the expansion board, so there is no need to manually connect the device.

image-20220326172612132

11.6. Experimental effect

After the program is programmed, the LED light flashes every 200 milliseconds. Open the serial port assistant (the parameters are as shown in the figure below), you can see that the serial port assistant has been printing the data of the MPU9250's accelerometer accel, gyroscope gyro, and magnetometer mag.

image-20220519104355685