Arduino for BPI:bit 15 : How to use MPU-9250 9-axis sensor

Banana Pi BPI:bit have a MPU-9250 9-axis sensor onboard , (triaxial acceleration Three-axis gyroscope and three-axis magnetic compass),

now we use BPI:bit + ArduinoIDE 1.8.9 learn to make a compass using the MPU9250 on the bpi-bit board

mainfunction

int MPU9250::setAccelRange(AccelRange range)

int MPU9250::setGyroRange(GyroRange range)

int MPU9250::setDlpfBandwidth(DlpfBandwidth bandwidth)

int MPU9250::calibrateMag()

double atan2(double y, double x)

Code

MPU9250 IMU(i2c0, 0x68);//V1.4
//we need to modify the I2C address according to the hardware.
//Hardware Version 1.2   >MPU9250 IMU(i2c0, 0x69);<
//Hardware Version 1.4   >MPU9250 IMU(i2c0, 0x68);<

Create an MPU9250 object.I2c0 is the pin of I2C, 0x68 is the address of I2C

(if bpi:bit hardware version 1.2, the address of I2C is 0x69)

Serial.printf("\r\n Yaw %.6f ", float(atan2(IMU.getMagY_uT(), IMU.getMagX_uT())) * RAD_TO_DEG);
  delay(20);

Print out the tilt in the x, y direction

To test your code, simply compile it using the Arduino IDE and upload it to the bpi:bit development board

#include "MPU9250.h"

MPU9250 IMU(i2c0, 0x68);//V1.4
//we need to modify the I2C address according to the hardware.
//Hardware Version 1.2   >MPU9250 IMU(i2c0, 0x69);<
//Hardware Version 1.4   >MPU9250 IMU(i2c0, 0x68);<

int status;

void setup()
{
  // serial to display data
  Serial.begin(9600);
  while (!Serial)
  {
  }
  // start communication with IMU
  status = IMU.begin();
  if (status < 0)
  {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while (1)
    {
    }
  }
  // setting the accelerometer full scale range to +/-8G
  IMU.setAccelRange(MPU9250::ACCEL_RANGE_2G);
  // setting the gyroscope full scale range to +/-500 deg/s
  IMU.setGyroRange(MPU9250::GYRO_RANGE_250DPS);
  // setting DLPF bandwidth to 20 Hz
  IMU.setDlpfBandwidth(MPU9250::DLPF_BANDWIDTH_41HZ);
  // setting SRD to 19 for a 50 Hz update rate
  // IMU.setSrd(19);
  IMU.calibrateMag();
}

#define RAD_TO_DEG 57.295779513082320876798154814105  // 180/π

void loop()
{
  // read the sensor
  IMU.readSensor();

  

  Serial.printf("\r\n Yaw %.6f ", float(atan2(IMU.getMagY_uT(), IMU.getMagX_uT())) * RAD_TO_DEG);
  delay(20);
}

test

The north-south Angle of the geomagnetic data obtained by the onboard MPU9250 magnetometer is returned through a serial port.

Angle and direction (LED panel up) :

方向 角度
+90
±180
西 -90
±0

reference ddocuments

MPU9250 lib

ESP32 chip