# How to get stable data from MPU9250?

**URL:** <https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888>\
**Category:** Programming\
**Created:** [May 22, 2024, 8:40am UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888 "2024-05-22T08:40:01Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![riazulislam20](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/riazulislam20/32/1098606_2.png) [@riazulislam20](https://forum.arduino.cc/u/riazulislam20)\
**Post date:** [May 22, 2024, 8:40am UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/1 "2024-05-22T08:40:01Z")

</div>

Hi,  
I have successfully made a device that will show North and inclination angle of the star "Polaris". But the data I am getting from MPU9250 is very fast, hence looks unstable. Can it be possible to get smoother reading as it shows almost 6 readings per loop!

TIA

```arduino
#include <SoftwareSerial.h>
#include<Wire.h>
#include "quaternionFilters.h"
#include "MPU9250.h"
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2Cclock 440000
#define I2Cport Wire
#define MPU9250_ADDRESS MPU9250_ADDRESS_AD0

MPU9250 myIMU(MPU9250_ADDRESS, I2Cport, I2Cclock);

//offset setting for North
float offsetCalibration = -0.5;

// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
int RXPin = 6;
int TXPin = 7; 
int GPSBaud = 9600; 
TinyGPSPlus gps;
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup() {
  Wire.begin();
  myIMU.initMPU9250();
  Serial.begin(115200);

  byte d = myIMU.readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);

  #if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(font5x7);
 uint32_t m = micros();
  gpsSerial.begin(GPSBaud);

    oled.set1X();
    oled.setCursor(0,0);  
    if (d == 0x48) {
      oled.println("Magnetometer Connected!");
    } else {
      oled.println("Magnetometer Failed!");
    }

  delay(2000);

  myIMU.initAK8963(myIMU.factoryMagCalibration);
  myIMU.getMres();
  myIMU.getAres();
  myIMU.getGres();
 

  oled.clear();
  oled.set2X();
    oled.setCursor(3,2);  
    oled.println("Wave now!");
    oled.set1X();
    oled.setCursor(1,5);  
    oled.println("Collecting data");

  // The next call delays for 4 seconds, and then records about 15 seconds of
  // data to calculate bias and scale.
  myIMU.magCalMPU9250(myIMU.magBias, myIMU.magScale);
  // myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias);

    oled.clear();
    oled.set2X();
    oled.setCursor(2,3);  
    oled.println("Calibrated");
  delay(5000);
  oled.clear();
}

void loop() {

 if (myIMU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
  {

    myIMU.readMagData(myIMU.magCount);

  myIMU.mx = (float)myIMU.magCount[0] * myIMU.mRes * myIMU.factoryMagCalibration[0] - myIMU.magBias[0];
  myIMU.my = (float)myIMU.magCount[1] * myIMU.mRes * myIMU.factoryMagCalibration[1] - myIMU.magBias[1];
  myIMU.mz = (float)myIMU.magCount[2] * myIMU.mRes * myIMU.factoryMagCalibration[2] - myIMU.magBias[2];

    myIMU.readAccelData(myIMU.accelCount); // Read the x/y/z adc values

    // Now we'll calculate the accleration value into actual g's
    // This depends on scale being set
    myIMU.ax = (float)myIMU.accelCount[0] * myIMU.aRes; // - myIMU.accelBias[0];
    myIMU.ay = (float)myIMU.accelCount[1] * myIMU.aRes; // - myIMU.accelBias[1];
    myIMU.az = (float)myIMU.accelCount[2] * myIMU.aRes; // - myIMU.accelBias[2];

    myIMU.readGyroData(myIMU.gyroCount); // Read the x/y/z adc values

    // Calculate the gyro value into actual degrees per second
    // This depends on scale being set
    myIMU.gx = (float)myIMU.gyroCount[0] * myIMU.gRes;
    myIMU.gy = (float)myIMU.gyroCount[1] * myIMU.gRes;
    myIMU.gz = (float)myIMU.gyroCount[2] * myIMU.gRes;

  }

    myIMU.updateTime();

     MahonyQuaternionUpdate(myIMU.ax, myIMU.ay, myIMU.az, myIMU.gx * DEG_TO_RAD,
                         myIMU.gy * DEG_TO_RAD, myIMU.gz * DEG_TO_RAD, myIMU.my,
                         myIMU.mx, myIMU.mz, myIMU.deltat);

  float heading = atan2(myIMU.mx, myIMU.my) + offsetCalibration;

  // How to get the magnetic declination angle
  // is available in the article https://bit.ly/3Zd6e2z
  float declination = -0.48;

  heading += declination;

  // Correct for when signs are reversed.
  if (heading < 0)
    heading += 2 * PI;

  // Check for wrap due to addition of declination.
  if (heading > 2 * PI)
    heading -= 2 * PI;

  float angle = (heading * 180 / M_PI);

  // myIMU.yaw = atan2(2.0f * (*(getQ()+1) * *(getQ()+2) + *getQ()
  // * *(getQ()+3)), *getQ() * *getQ() + *(getQ()+1)
  // * *(getQ()+1) - *(getQ()+2) * *(getQ()+2) - *(getQ()+3)
  // * *(getQ()+3));
  // myIMU.pitch = -asin(2.0f * (*(getQ()+1) * *(getQ()+3) - *getQ()
  // * *(getQ()+2)));
      myIMU.roll = atan2(2.0f * (*getQ() * *(getQ()+1) + *(getQ()+2)
                    * *(getQ()+3)), *getQ() * *getQ() - *(getQ()+1)
                    * *(getQ()+1) - *(getQ()+2) * *(getQ()+2) + *(getQ()+3)
                    * *(getQ()+3));
      // myIMU.pitch *= RAD_TO_DEG;
      // myIMU.yaw *= RAD_TO_DEG;

      // Declination of SparkFun Electronics (40°05'26.6"N 105°11'05.9"W) is
      // 8° 30' E ± 0° 21' (or 8.5°) on 2016-07-19
      // - http://www.ngdc.noaa.gov/geomag-web/#declination
      myIMU.yaw -= 0.30;
      myIMU.roll *= RAD_TO_DEG;
     float roll = map(myIMU.roll, -180, 180, 360, 0);

while (gpsSerial.available() > 0)
    if (gps.encode(gpsSerial.read()))
      // oled.clear();
  oled.set1X();
    oled.setCursor(0,0);      
     oled.println(F("LAT: "));
     oled.set1X();
     oled.clear(50, 200, 0, 0);
     oled.setCursor(60,0);
     oled.set1X();
     oled.print(gps.location.lat(), 4);
     double lat=gps.location.lat();
     oled.clear(50, 200, 1, 1);
     oled.set1X();
     oled.setCursor(0,1);
      oled.println(F("LONG: "));
      oled.set1X();
      oled.setCursor(60,1);
     oled.print(gps.location.lng(), 4);
     oled.set1X();
     oled.setCursor(0,2);      
      oled.print(F("Sat: "));
      oled.clear(30, 48, 2, 3);
      oled.set1X();
     oled.setCursor(30,2);
      oled.print(gps.satellites.value());
// oled.setCursor(45,3);
// oled.print(gps.time.minute());
// oled.setCursor(60,3);
// oled.print(gps.time.second());
oled.set1X();
     oled.setCursor(50,2);      
      oled.print(F("Alt: "));
      oled.clear(75, 200, 2, 3);
      oled.set1X();
     oled.setCursor(80,2);
      oled.print(gps.altitude.feet());

   oled.set2X();
     oled.setCursor(0,4);
     oled.print(F("North: "));
      oled.setCursor(80,4);
      oled.clear(70, 200, 4, 10);
      oled.set2X();
   oled.print(angle, 0);

    oled.setCursor(0,6);
   oled.print(F("Angle: "));
   oled.setCursor(80,6);
if (
  (gps.satellites.value() > 0))
  {
    oled.set2X();
  oled.setCursor(70,6);
   oled.print((lat-(myIMU.roll)),0); // roll to be included - (myIMU.roll, 0)
  }
else
{
  oled.set1X();
  oled.setCursor(70,6);
   oled.print("Searching...."); // "noGPS"
}
oled.set1X();
// oled.setCursor(0,7);
// oled.print(roll, 0);
// // Serial.print(myIMU.roll);
// // Serial.print(roll, 0);
// // oled.setCursor(40,7);
// // oled.print(myIMU.yaw);
// oled.setCursor(80,7);
// oled.print(myIMU.roll, 0);  
// // delay(20);
}

```

Update:  
Solution found. The modified code:

```arduino
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include "quaternionFilters.h"
#include "MPU9250.h"
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2Cclock 400000
#define I2Cport Wire
#define MPU9250_ADDRESS MPU9250_ADDRESS_AD0
MPU9250 myIMU(MPU9250_ADDRESS, I2Cport, I2Cclock);

//offset setting for North
float offsetCalibration = -0.5;

// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
int RXPin = 6;
int TXPin = 7; 
int GPSBaud = 9600; 
TinyGPSPlus gps;
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup() {
  Wire.begin();
  // myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias);
  myIMU.initMPU9250();
  // Serial.begin(115200);

  byte d = myIMU.readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);

  #if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(font5x7);
 uint32_t m = micros();
  gpsSerial.begin(GPSBaud);

    oled.set1X();
    oled.setCursor(0,0);  
    if (d == 0x48) {
      oled.println("Magnetometer Connected!");
    } else {
      oled.println("Magnetometer Failed!");
    }

  delay(2000);

  myIMU.initAK8963(myIMU.factoryMagCalibration);
  myIMU.getMres();
  myIMU.getAres();
  myIMU.getGres();
 

  oled.clear();
  oled.set2X();
    oled.setCursor(3,2);  
    oled.println("Wave now!");
    oled.set1X();
    oled.setCursor(1,5);  
    oled.println("Collecting data");

  // The next call delays for 4 seconds, and then records about 15 seconds of
  // data to calculate bias and scale.
  myIMU.magCalMPU9250(myIMU.magBias, myIMU.magScale);
  // myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias);

    oled.clear();
    oled.set2X();
    oled.setCursor(2,3);  
    oled.println("Calibrated");
  delay(5000);
  oled.clear();
}

void loop() {

 if (myIMU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
  {

    myIMU.readMagData(myIMU.magCount);

  myIMU.mx = (float)myIMU.magCount[0] * myIMU.mRes * myIMU.factoryMagCalibration[0] - myIMU.magBias[0];
  myIMU.my = (float)myIMU.magCount[1] * myIMU.mRes * myIMU.factoryMagCalibration[1] - myIMU.magBias[1];
  myIMU.mz = (float)myIMU.magCount[2] * myIMU.mRes * myIMU.factoryMagCalibration[2] - myIMU.magBias[2];

    myIMU.readAccelData(myIMU.accelCount); // Read the x/y/z adc values

    // Now we'll calculate the accleration value into actual g's
    // This depends on scale being set
    myIMU.ax = (float)myIMU.accelCount[0] * myIMU.aRes; // - myIMU.accelBias[0];
    myIMU.ay = (float)myIMU.accelCount[1] * myIMU.aRes; // - myIMU.accelBias[1];
    myIMU.az = (float)myIMU.accelCount[2] * myIMU.aRes; // - myIMU.accelBias[2];

    myIMU.readGyroData(myIMU.gyroCount); // Read the x/y/z adc values

    // Calculate the gyro value into actual degrees per second
    // This depends on scale being set
    myIMU.gx = (float)myIMU.gyroCount[0] * myIMU.gRes;
    myIMU.gy = (float)myIMU.gyroCount[1] * myIMU.gRes;
    myIMU.gz = (float)myIMU.gyroCount[2] * myIMU.gRes;

  }

    myIMU.updateTime();

     MahonyQuaternionUpdate(myIMU.ax, myIMU.ay, myIMU.az, myIMU.gx * DEG_TO_RAD,
                         myIMU.gy * DEG_TO_RAD, myIMU.gz * DEG_TO_RAD, myIMU.my,
                         myIMU.mx, myIMU.mz, myIMU.deltat);

    // MahonyQuaternionUpdate(myIMU.ax, myIMU.ay, myIMU.az, myIMU.gx * DEG_TO_RAD,
    // myIMU.gy * DEG_TO_RAD, myIMU.gz * DEG_TO_RAD, myIMU.my,
    // myIMU.mx, -myIMU.mz, myIMU.deltat);                       

  float heading = atan2(myIMU.mx, myIMU.my) + offsetCalibration;

  // How to get the magnetic declination angle
  // is available in the article https://bit.ly/3Zd6e2z
  float declination = -0.48;

  heading += declination;

  // Correct for when signs are reversed.
  if (heading < 0)
    heading += 2 * PI;

  // Check for wrap due to addition of declination.
  if (heading > 2 * PI)
    heading -= 2 * PI;

// float average_heading = 0;
// for (int i=0; i < 100; i++) {
// average_heading = average_heading + heading;
// }
// average_heading = average_heading/100;

  // float angle = (average_heading * 180 / M_PI);
  float angle = (heading * 180 / M_PI);

  // myIMU.yaw = atan2(2.0f * (*(getQ()+1) * *(getQ()+2) + *getQ()
  // * *(getQ()+3)), *getQ() * *getQ() + *(getQ()+1)
  // * *(getQ()+1) - *(getQ()+2) * *(getQ()+2) - *(getQ()+3)
  // * *(getQ()+3));
  // myIMU.pitch = -asin(2.0f * (*(getQ()+1) * *(getQ()+3) - *getQ()
  // * *(getQ()+2)));
      // myIMU.roll = atan2(2.0f * (*getQ() * *(getQ()+1) + *(getQ()+2)
      // * *(getQ()+3)), *getQ() * *getQ() - *(getQ()+1)
      // * *(getQ()+1) - *(getQ()+2) * *(getQ()+2) + *(getQ()+3)
      // * *(getQ()+3));

 myIMU.delt_t = millis() - myIMU.count;

    // update LCD once per half-second independent of read rate
    if (myIMU.delt_t > 500)
    {      

          myIMU.roll = atan2(2.0f * (*getQ() * *(getQ() + 1) + * (getQ() + 2)
                                  * *(getQ() + 3)), *getQ() * *getQ() - * (getQ() + 1)
                          * *(getQ() + 1) - * (getQ() + 2) * *(getQ() + 2) + * (getQ() + 3)
                          * *(getQ() + 3));                
      // myIMU.pitch *= RAD_TO_DEG;
      // myIMU.yaw *= RAD_TO_DEG;

      // Declination of SparkFun Electronics (40°05'26.6"N 105°11'05.9"W) is
      // 8° 30' E ± 0° 21' (or 8.5°) on 2016-07-19
      // - http://www.ngdc.noaa.gov/geomag-web/#declination
      myIMU.yaw -= 0.30;
      myIMU.roll *= RAD_TO_DEG;
     float roll = myIMU.roll;

     //avarage values

// float average_roll = 0;
// for (int j=0; j < 500; j++) {
// average_roll = average_roll + roll;
// }
// average_roll = average_roll/500;
    

while (gpsSerial.available() > 0)
    if (gps.encode(gpsSerial.read()))
      // oled.clear();
  oled.set1X();
    oled.setCursor(0,0);      
     oled.println(F("LAT: "));
     oled.set1X();
     oled.clear(50, 200, 0, 0);
     oled.setCursor(60,0);
     oled.set1X();
     oled.print(gps.location.lat(), 6);
     double lat=gps.location.lat();
     oled.clear(50, 200, 1, 1);
     oled.set1X();
     oled.setCursor(0,1);
      oled.println(F("LONG: "));
      oled.set1X();
      oled.setCursor(60,1);
     oled.print(gps.location.lng(), 6);
     oled.set1X();
     oled.setCursor(0,2);      
      oled.print(F("Sat: "));
      oled.clear(30, 48, 2, 2);
      oled.set1X();
     oled.setCursor(30,2);
      oled.print(gps.satellites.value());
      oled.set1X();
     oled.setCursor(50,2);      
      oled.print(F("Alt: "));
      oled.clear(75, 200, 2, 2);
      oled.set1X();
     oled.setCursor(80,2);
      oled.print(gps.altitude.feet());
      oled.set1X();
       oled.setCursor(0,3);
    oled.println("DATE: "); 
    oled.clear(40, 100, 3, 3);
    oled.set1X();
    oled.setCursor(40,3);
    oled.print(gps.date.day());
    oled.setCursor(55,3);
    oled.print(gps.date.month());
    oled.setCursor(70,3);
    oled.print(gps.date.year());

    

   oled.set2X();
     oled.setCursor(0,4);
     oled.print(F("North: "));
      oled.setCursor(80,4);
      oled.clear(70, 200, 4, 10);
      oled.set2X();
   oled.println(angle, 0);
      oled.setCursor(106,4);
      oled.set1X();
   oled.println("0");
    oled.setCursor(0,6);
    oled.set2X();
   oled.print(F("Angle: "));
   oled.setCursor(80,6);
if (
  (gps.location.lat() > 0))
  {
    oled.set2X();
  oled.setCursor(70,6);
   oled.print((lat-roll),0); // roll to be included - (myIMU.roll, 0)
  }
else
{
  oled.set1X();
  oled.setCursor(70,6);
   oled.print(roll, 0); // "noGPS"
}
oled.set1X();
// oled.setCursor(0,7);
// oled.print(roll, 0);
// // Serial.print(myIMU.roll);
// // Serial.print(roll, 0);
// // oled.setCursor(40,7);
// // oled.print(myIMU.yaw);
// oled.setCursor(80,7);
// oled.print(myIMU.roll, 0);  
  // delay(20);

   myIMU.count = millis();
      myIMU.sumCount = 0;
      myIMU.sum = 0;
    } // if (myIMU.delt_t > 500)
}

```

---

<div class="post-metadata">

**Author:** ![bluejets](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/bluejets/32/1013044_2.png) [@bluejets](https://forum.arduino.cc/u/bluejets)\
**Post date:** [May 22, 2024, 8:43am UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/2 "2024-05-22T08:43:27Z")

</div>

how about a short delay in the loop?

---

<div class="post-metadata">

**Author:** ![riazulislam20](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/riazulislam20/32/1098606_2.png) [@riazulislam20](https://forum.arduino.cc/u/riazulislam20)\
**Post date:** [May 22, 2024, 9:55am UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/3 "2024-05-22T09:55:45Z")

</div>

Tried with 20 and 120ms. Worsen. Problem is its giving more than 6 data/loop

---

<div class="post-metadata">

**Author:** ![dThirteen](https://avatars.discourse-cdn.com/v4/letter/d/ecc23a/32.png) [@dThirteen](https://forum.arduino.cc/u/dThirteen)\
**Post date:** [May 22, 2024, 9:39pm UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/4 "2024-05-22T21:39:06Z")

</div>

Try a Simple Kalman Filter. You should find it in your Library Manager. Just remember it predicts the current value based on the previous value and the current sensor reading, so it will tend to have at least a one-cycle delay in responding to changes. If you need instant response, this -might- have some effect. Try it and see.

> **[SimpleKalmanFilter - Arduino Reference](https://www.arduino.cc/reference/en/libraries/simplekalmanfilter/)**
>
> The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.

---

<div class="post-metadata">

**Author:** ![JohnRob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/johnrob/32/253560_2.png) [@JohnRob](https://forum.arduino.cc/u/JohnRob)\
**Post date:** [May 22, 2024, 9:42pm UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/5 "2024-05-22T21:42:32Z")

</div>

You need to tell us what the actual non stability is. Unfortunately in the real (analog) world nothing is perfectly stable, there is always random noise, vibration etc.

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [May 22, 2024, 9:43pm UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/6 "2024-05-22T21:43:08Z")

</div>

> [@riazulislam20](#):
>
> Can it be possible to get smoother reading as it shows almost 6 readings per loop!

Yes, especially if you average some number of readings together before displaying the result.

This is _completely_ unnecessary, and inaccurate, because the Mahony filter effectively includes a tilt compensated compass calculation (i.e. the yaw angle).

```arduino
  float heading = atan2(myIMU.mx, myIMU.my) + offsetCalibration;

```

Also, the Mahony filter will work much, much better if you carefully calibrate the magnetometer and the accelerometer according to this procedure:

> **[Tutorial: How to calibrate a compass (and accelerometer) with Arduino](https://thecavepearlproject.org/2015/05/22/calibrating-any-compass-or-accelerometer-for-arduino/)**
>
> When I started building a flow sensor based on the drag/tilt principle, I knew that leaving sensors on their default factory calibration settings was not optimal, but I had so many other things to …

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [November 18, 2024, 9:43pm UTC](https://forum.arduino.cc/t/how-to-get-stable-data-from-mpu9250/1262888/7 "2024-11-18T21:43:19Z")

</div>

Closed on November 18, 2024, 9:43pm UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
