GithubHelp home page GithubHelp logo

mpu9250's Introduction

MPU-9250

Arduino sketch for MPU-9250 9 DoF sensor with AHRS sensor fusion

Most modern and correct version is: MPU9250_MS5637_AHRS_t3.ino, all require quaternionFilters.ino in the IDE folder also to use the Madgwick and/or Mahony sensor fusion algorithms.

Demonstrate MPU-9250 basic functionality including parameterizing the register addresses, initializing the sensor, getting properly scaled accelerometer, gyroscope, and magnetometer data out, calibration and self-test of sensors. Added display functions to allow display to on-breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1.

A discussion of the use and limitations of this sensor and sensor fusion in general is found here.

I have also added a program to allow sensor fusion using the MPU-9250 9-axis motion sensor with the STM32F401 Nucleo board using the mbed compiler. The STM32F401 achieves a sensor fusion filter update rate using the Madgwick MARG fusion filter of 4800 Hz running the M4 Cortex ARM processor at 84 MHz; compare to the sensor fusion update rate of 2120 Hz achieved using the same filter with the Teensy 3.1 running its M4 Cortex ARM processor at 96 MHz.

One reason for this difference is the single-precision floating point engine embedded in the STM32F401 core. While both ARM processors achieve impressive rates of filtering, really more than necessary for most applications, the factor of two difference translates into much lower power consumption for the same sensor fusion performance. If adequate sensor fusion filtering, say, 1000 Hz, can be achieved at much lower processor clock speed, then over all power consumption will be reduced. This really matters for wearable and other portable motion sensing and control applications.

I added a version of the basic sketch that uses the i2c_t3.h 'Wire' library specifically designed for Teensy 3.1. It allows easy access to Teensy-specific capabilities such as specification of which set of hardware i2c pins will be used, the bus speed (up to 1 MHz!) and also allows master and/or slave designation to handle multiplexing between i2c devices. See www.pjrc.com/teensy and http://forum.pjrc.com/threads/21680-New-I2C-library-for-Teensy3 for details.

I added another version of the sketch intended specifically for the MPU9250_MS5637 Mini Add-On shield for the Teensy 3.1.

MPU9250 + MS5637 Micro (left) and Mini (right) add-on shields, which solder onto the bottom pads 23-34 or pins 8 -17 on the Teensy 3.1, respectively.

It can be simply modified to work with the corresponding micro shield as well. It uses SDA/SCL on pins 17/16, respectively, and it uses the Teensy 3.1-specific Wire library i2c_t3.h. The MS5637 is a simple but high resolution pressure sensor, which can be used in its high resolution mode with power consumption of 20 microAmp, or in a lower resolution mode with power consumption of only 1 microAmp. The choice will depend on the application. The sketch calculates and outputs temperature in degrees Centigrade, pressure in millibar, and altitude in feet. In high resolution mode, the pressure is accurate to within 10 Pa or 0.1 millibar, and the height discrimination is about 13 cm. This is much better performance than achievable from the venerable MPL3115A2 and the MS5637 is in a very small package perfect for the small micro and mini add-on Teensy 3.1 shields.

For a discussion of the relative merits of modern board-mounted pressure sensors, see here.

I added sketches for the various new Mini add-on shields for Teensy 3.1 with the MPU9250 9-axis motion sensor and either the MPL3115A2 or the newer LPS25H pressure sensor/altimeter. Now there are three flavors of 10 DoF Mini add-on boards specially designed for the Teensy 3.1 with state-of-the-art 20-bit (MPL3115A2) and 24-bit (MS5637 and LPS25H) altimeters. The LPS25H has a 32-byte FIFO and sophisticated hardware filtering which allows very low power operation while maintaining 0.01 millibar resolution. This is really quite a feat; this sensor deserves serious consideration for any airborne application you might have in mind.

mpu9250's People

Contributors

alexozer avatar eric-wieser avatar kriswiner avatar mikefair avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mpu9250's Issues

Angles changes when I move.

Hey Kris, thank you for sharing your code.
Well I'm using a µC cortex M3 at 77MHz.
I sample IMU at 50Hz and fusion at 1000Hz using Madwick algo.
Firstly I calibrated my imu and my compass with your code:

void magcalMPU9250(float * dest1, float * dest2)
{
uint16_t ii = 0, sample_count = 0;
int32_t mag_bias[3] = {0, 0, 0}, mag_scale[3] = {0, 0, 0};
int16_t mag_max[3] = {0xF000, 0xF000, 0xF000}, mag_min[3] = {0x7FFF, 0x7FFF, 0x7FFF}, mag_temp[3] = {0, 0, 0};

CyDelay(4000);

sample_count = 128;
for(ii = 0; ii < sample_count; ii++) {
readMagData(mag_temp); // Read the mag data
int jj = 0;
for (jj = 0; jj < 3; jj++) {
if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj];
if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj];
}
CyDelay(12); // at 8 Hz ODR, new mag data is available every 125 ms
}

// Get hard iron correction
mag_bias[0] = (mag_max[0] + mag_min[0])/2; // get average x mag bias in counts
mag_bias[1] = (mag_max[1] + mag_min[1])/2; // get average y mag bias in counts
mag_bias[2] = (mag_max[2] + mag_min[2])/2; // get average z mag bias in counts

dest1[0] = (float) mag_bias[0]_mRes_magCalibration[0]; // save mag biases in G for main program
dest1[1] = (float) mag_bias[1]_mRes_magCalibration[1];
dest1[2] = (float) mag_bias[2]_mRes_magCalibration[2];

// Get soft iron correction estimate
mag_scale[0] = (mag_max[0] - mag_min[0])/2; // get average x axis max chord length in counts
mag_scale[1] = (mag_max[1] - mag_min[1])/2; // get average y axis max chord length in counts
mag_scale[2] = (mag_max[2] - mag_min[2])/2; // get average z axis max chord length in counts

float avg_rad = mag_scale[0] + mag_scale[1] + mag_scale[2];
avg_rad /= 3.0;

dest2[0] = avg_rad/((float)mag_scale[0]);
dest2[1] = avg_rad/((float)mag_scale[1]);
dest2[2] = avg_rad/((float)mag_scale[2]);

}

well,
the code works but if I rotate on one axe, I got the good angle, but angles on other axes change too. As you said here: ''fusion rate is small compared to your sample data rate (likely with the 8 MHz Pro Mini) and/or your sensors are not properly bias calibrated''
#26

But in my case 50Hz IMUcompare to 1000Hz fusion seems enough, and my IMU is calibrate.

So if you have any suggestions?

Thank you very much

Quaternions get unstable when Pitch approaches +90 or -90?

Hi Kris,

I am trying to get quaternions from the MadgwickQuaternionUpdate Function. I am not converting them into euler angles as I know they suffer from gimble lock problem.

So at the start I am getting nice quaternions like [1,0,0,0] but when I increase the pitch of my sensor to 90 degree I am expecting to get quaternions like [0.707, 0, 0.707, 0] but I am not getting them instead random quaternions start developing in yaw and roll axes.

I don't know why this is happening, pls help in you have any idea about this. Thanks

doubt in function getMres()

hey kris,
it would be helpful for me if you can tell the reason for multiplying 10 with (4912/32760), i got to know that 4912 is magnetic flux density and 32760 is the range of magnetometer.....i found a formula in net HuT = H * 4912/32760 where H is raw data, but why are you multiplying by 10.....is it a constant? i am using ak8975....should i use the same formula? can you please justify?

thanks in advanc

Apparently this is not working for the acceleration biases in the MPU-9250

Hi

I've been porting your code to run in MMBasic on the Micromite.

I think I've solved this issue unless it is already solved and the comment out of date.

The problem comes because the offsets are 15-bit signed numbers stored in the 15 most significant bits with bit 0 used for whatever. My clunky Basic code which seems to work properly is

` readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, rData()) ' Read factory accelerometer trim values
accel_bias_reg(0) = iint15((rData(0) << 7) OR ((rData(1) and &HFE)>>1))
if rData(1) and &H1 then mask_bit(0)=&H1
readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, rData())
accel_bias_reg(1) = iint15((rData(0) << 7) OR ((rData(1) and &HFE)>>1))
if rData(1) and &H1 then mask_bit(1)=&H1
readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, rData())
accel_bias_reg(2) = iint15((rData(0) << 7) OR ((rData(1) and &HFE)>>1))
if rData(1) and &H1 then mask_bit(2)=&H1

' Construct total accelerometer bias, including calculated average accelerometer bias from above
accel_bias_reg(0) = accel_bias_reg(0) - (accel_bias(0)/8) ' Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg(1) = accel_bias_reg(1) - (accel_bias(1)/8)
accel_bias_reg(2) = accel_bias_reg(2) - (accel_bias(2)/8)
rData(0) = (accel_bias_reg(0) \ 128) AND &HFF
rData(1) = ((accel_bias_reg(0))<<1 ) AND &HFE
rData(1) = rData(1) OR mask_bit(0) ' preserve temperature compensation bit when writing back to accelerometer bias registers
rData(2) = (accel_bias_reg(1) \ 128) AND &HFF
rData(3) = ((accel_bias_reg(1)) <<1) AND &HFE
rData(3) = rData(3) OR mask_bit(1) ' preserve temperature compensation bit when writing back to accelerometer bias registers
rData(4) = (accel_bias_reg(2) \ 128) AND &HFF
rData(5) = ((accel_bias_reg(2))<<1) AND &HFE
rData(5) = rData(5) OR mask_bit(2) ' preserve temperature compensation bit when writing back to accelerometer bias registers
`

iint15 just dose a sign extend and I use integer division () because >> doesn't bring in the sign bit in MMBasic. Hopefully though you can see what I am doing

Different Chip breakouts: VDDI = ADO

Hello! This isn't an issue as much as a note:
I have one of these breakouts
616qjzhgoyl sl1001

and there isn't a VDDI pin so I wasn't sure how to connect the breakout to power in the proper way. I did some schematic cross-examination and figured out that it is the same as the "ADO" pin on the alternative breakout configuration (the one available on amazon.com). Just thought I'd post that so y'all wouldn't have to go to the trouble I did to figure it out.

Changing the Baud Rate Doesn't Change Serial.Print Speed!

Thanks for the Code, It works well!
The only problem is: When I change the baud rate (Serial.begin(...)) to a new value speed of Serial.print doesnt change! I mean there is no difference between Serial.begin(115200) and Serial.begin(9600) while serial printing.
Would you please let me know what I can do to have higher speeds of serial.print?
Thanks
Navid

Problems related to magnetometer

Hi Kris,
Thanks for sharing your codding. I'm trying to implement AHRS using MPU9250 and stm32 MCU. I use DMA to read data at freq=1.6Khz (except magnetometer), ant it works perfect. The filter update routine is also going on 1.6khz without problems (because of hardware FPU), but the overall results are pretty bad. First of all I have very strange overshoots (every axis), second thing is that changing pitch angle cause changing yaw angle. I think that it's related to magnetometer, because I can find where the magnetic field inclination is taking under consideration.... (or maybe I don't understand how it works...
Also the calculated angles are not stable, even if device is not moving, it changes +/- 1-2 deg.
I definitely not related to gyro because simple integration works perfect (except drift about 1deg/minute).
Could you please give me some advice how to start to fix the problems.
Best regards
Krzysiek

Magnetometer calibration question

Hello, this might have a very obvious question, but I've plotted my magnetometer values on a 3D scatter graph, the next step in the wiki is the use the code you state, which is this:

void magcalMPU9250(float * dest1, float * dest2)
{
uint16_t ii = 0, sample_count = 0;
int32_t mag_bias[3] = {0, 0, 0}, mag_scale[3] = {0, 0, 0};
int16_t mag_max[3] = {0xF000, 0xF000, 0xF000}, mag_min[3] = {0x7FFF, 0x7FFF, 0x7FFF}, mag_temp[3] = {0, 0, 0};

Serial.println("Mag Calibration: Wave device in a figure eight until done!");
delay(4000);

sample_count = 128;
for(ii = 0; ii < sample_count; ii++) {
MPU9250readMagData(mag_temp); // Read the mag data
for (int jj = 0; jj < 3; jj++) {
if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj];
if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj];
}
delay(135); // at 8 Hz ODR, new mag data is available every 125 ms
}

// Get hard iron correction
mag_bias[0] = (mag_max[0] + mag_min[0])/2; // get average x mag bias in counts
mag_bias[1] = (mag_max[1] + mag_min[1])/2; // get average y mag bias in counts
mag_bias[2] = (mag_max[2] + mag_min[2])/2; // get average z mag bias in counts

dest1[0] = (float) mag_bias[0]_MPU9250mRes_MPU9250magCalibration[0]; // save mag biases in G for main program
dest1[1] = (float) mag_bias[1]_MPU9250mRes_MPU9250magCalibration[1];
dest1[2] = (float) mag_bias[2]_MPU9250mRes_MPU9250magCalibration[2];

// Get soft iron correction estimate
mag_scale[0] = (mag_max[0] - mag_min[0])/2; // get average x axis max chord length in counts
mag_scale[1] = (mag_max[1] - mag_min[1])/2; // get average y axis max chord length in counts
mag_scale[2] = (mag_max[2] - mag_min[2])/2; // get average z axis max chord length in counts

float avg_rad = mag_scale[0] + mag_scale[1] + mag_scale[2];
avg_rad /= 3.0;

dest2[0] = avg_rad/((float)mag_scale[0]);
dest2[1] = avg_rad/((float)mag_scale[1]);
dest2[2] = avg_rad/((float)mag_scale[2]);

Serial.println("Mag Calibration done!");
}

My question is where does this go? Do I start a new sketch with it, or add it into existing one? Or am I wrong and confused all together? Thanks for the help

Madgwick-Filter-ODR / Filtered-Magnetometer-Data

Hey Kris,

after some nicely spent vacation time I am now back to put all my effort into my little sensor-project and I do have a few more questions I would like to discuss with you.

I pretty much got your MPU9250-template set up for a CSR1010-MPU9250-combo-board and a smartphone as receiver/mc. For some reason I am not seeing any nice and stable roll, pitch and yaw angles which freaks me out...

Ok I have to admit that through my never ending researches for calibration approaches, madgwick fixes (s-parameters, inv-sqrt, ...) and other things I might have made too many adjustments and tweaks along the way! So now its „almost“ back to the start, taking your work as baseline and take it on from there (again)...

Now to the questions:

  1. How is the function-call-frequency of your loop()-routine determined? Is there a start-skript somewhere or does it get called automatically? In other words how do you get/calculate a filter ODR of 145 hz?
  2. If I am sampling my sensor data at 50 hz continuously, what kind of filter ODR would you propose? Should it always be at least 200 hz? (Currently doing just 50 hz when the data is coming in, which doesnt seem to do that well...)
  3. What readout-frequency you use for your magnetometer? If I saw it correctly its always just 8 hz instead of 100 hz – only due to the readout-latency?
  4. How does all the calibration data from the magnetometer calibration needs to be applied to the raw sensor data?

Heres my approach:

scaledData[Tag.MAGNETOMETER][i] = (rawData[Tag.MAGNETOMETER][i] \* magResolution \* currCalibrationData.magSensitivity[i] - currCalibrationData.magBias[i] \* magResolution \* currCalibrationData.magSensitivity[i]) \* currCalibrationData.magScale[i]; 
Legend:

i ~ x-, y-, z-axis
currCalibrationData.magSensitivity[i] = (((rawSensitivityAdjustmentValue[i] - 128.0f) * 0.5f) / 128.0f + 1.0f);
magResolution = 10.0f * 4912.0f / 32760.0f;

I would very much appreciate your help!

Thanks in advance

Ray

I2C bypass enabled is creating issues

I have tried mpu9250 init code you wrote and the moment i set the BYPASS_EN bit to 1 the I2C bus goes berserk
(INT_PIN_CFG, 0bxxxxxx1x) # BYPASS_EN = 1
(USER_CTRL, 0bxx0xxxxx) # I2C_MST_EN = 0
i see in the docs the below note, is there any way we can explicitly disable those pull-ups ? (my impression was that if 12c master is disabled and bypass is enabled the internal pull ups should be disabled)
When asserted, the i2c_master interface pins(ES_CL and ES_DA) will go into ‘bypass mode’ when the i2c master interface is disabled. The pins will float high due to the internal pull-up if not enabled and the i2c master interface is disabled.

after the bypass gets enable the signal looks like it's pulled too much up or the 0 reference is totally off
bad

nice clean bus prior to enabling the bypass
good

anyway any idea what is causing this and what setting must be made to properly enable the bypass.

MPU-9250 and SPI code

/* MPU9250 Basic Example Code
by: Kris Winer
date: April 1, 2014
license: Beerware - Use this code however you'd like. If you
find it useful you can buy me a beer some time.

Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor,
getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to
allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and
Mahony filter algorithms. Sketch runs on Arduino.

Hardware setup:
MPU9250 Breakout --------- Arduino
VCC ---------------------- 5V
SCLK --------------------- 13
SDI ----------------------- 11
SDO ----------------------- 12
NSC ----------------------- 10
GND ---------------------- GND

Note: The MPU9250 and SPI
*/

include <SPI.h>

define NCS_PIN 10

define MOSI_PIN 11

define MISO_PIN 12

define SCK_PIN 13

const int NCS = NCS_PIN;

uint8_t SPI_read_register( uint8_t reg )
{
digitalWrite( NCS, LOW);
SPI.transfer( reg | 0x80 ); // reg | 0x80 to denote read
uint8_t read_value = SPI.transfer( 0x00 ); // write 8-bits zero
digitalWrite( NCS, HIGH);
return read_value;
}

/************************************************************************/

void SPI_write_register( uint8_t reg, uint8_t value )
{
digitalWrite( NCS, LOW);
SPI.transfer( reg );
SPI.transfer( value );
digitalWrite( NCS, HIGH);
}

// See also MPU-9250 Register Map and Descriptions, Revision 4.0, RM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in
// above document; the MPU9250 and MPU9150 are virtually identical but the latter has a different register map
//
//Magnetometer Registers

define AK8963_ADDRESS 0x0C

define WHO_AM_I_AK8963 0x00 // should return 0x48

define INFO 0x01

define AK8963_ST1 0x02 // data ready status bit 0

define AK8963_XOUT_L 0x03 // data

define AK8963_XOUT_H 0x04

define AK8963_YOUT_L 0x05

define AK8963_YOUT_H 0x06

define AK8963_ZOUT_L 0x07

define AK8963_ZOUT_H 0x08

define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status bit 2

define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0

define AK8963_ASTC 0x0C // Self test control

define AK8963_I2CDIS 0x0F // I2C disable

define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value

define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value

define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value

define SELF_TEST_X_GYRO 0x00

define SELF_TEST_Y_GYRO 0x01

define SELF_TEST_Z_GYRO 0x02

/*#define X_FINE_GAIN 0x03 // [7:0] fine gain

define Y_FINE_GAIN 0x04

define Z_FINE_GAIN 0x05

define XA_OFFSET_H 0x06 // User-defined trim values for accelerometer

define XA_OFFSET_L_TC 0x07

define YA_OFFSET_H 0x08

define YA_OFFSET_L_TC 0x09

define ZA_OFFSET_H 0x0A

define ZA_OFFSET_L_TC 0x0B */

define SELF_TEST_X_ACCEL 0x0D

define SELF_TEST_Y_ACCEL 0x0E

define SELF_TEST_Z_ACCEL 0x0F

define SELF_TEST_A 0x10

define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope

define XG_OFFSET_L 0x14

define YG_OFFSET_H 0x15

define YG_OFFSET_L 0x16

define ZG_OFFSET_H 0x17

define ZG_OFFSET_L 0x18

define SMPLRT_DIV 0x19

define CONFIG 0x1A

define GYRO_CONFIG 0x1B

define ACCEL_CONFIG 0x1C

define ACCEL_CONFIG2 0x1D

define LP_ACCEL_ODR 0x1E

define WOM_THR 0x1F

define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms

define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0]

define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms

define FIFO_EN 0x23

define I2C_MST_CTRL 0x24

define I2C_SLV0_ADDR 0x25

define I2C_SLV0_REG 0x26

define I2C_SLV0_CTRL 0x27

define I2C_SLV1_ADDR 0x28

define I2C_SLV1_REG 0x29

define I2C_SLV1_CTRL 0x2A

define I2C_SLV2_ADDR 0x2B

define I2C_SLV2_REG 0x2C

define I2C_SLV2_CTRL 0x2D

define I2C_SLV3_ADDR 0x2E

define I2C_SLV3_REG 0x2F

define I2C_SLV3_CTRL 0x30

define I2C_SLV4_ADDR 0x31

define I2C_SLV4_REG 0x32

define I2C_SLV4_DO 0x33

define I2C_SLV4_CTRL 0x34

define I2C_SLV4_DI 0x35

define I2C_MST_STATUS 0x36

define INT_PIN_CFG 0x37

define INT_ENABLE 0x38

define DMP_INT_STATUS 0x39 // Check DMP interrupt

define INT_STATUS 0x3A

define ACCEL_XOUT_H 0x3B

define ACCEL_XOUT_L 0x3C

define ACCEL_YOUT_H 0x3D

define ACCEL_YOUT_L 0x3E

define ACCEL_ZOUT_H 0x3F

define ACCEL_ZOUT_L 0x40

define TEMP_OUT_H 0x41

define TEMP_OUT_L 0x42

define GYRO_XOUT_H 0x43

define GYRO_XOUT_L 0x44

define GYRO_YOUT_H 0x45

define GYRO_YOUT_L 0x46

define GYRO_ZOUT_H 0x47

define GYRO_ZOUT_L 0x48

define EXT_SENS_DATA_00 0x49

define EXT_SENS_DATA_01 0x4A

define EXT_SENS_DATA_02 0x4B

define EXT_SENS_DATA_03 0x4C

define EXT_SENS_DATA_04 0x4D

define EXT_SENS_DATA_05 0x4E

define EXT_SENS_DATA_06 0x4F

define EXT_SENS_DATA_07 0x50

define EXT_SENS_DATA_08 0x51

define EXT_SENS_DATA_09 0x52

define EXT_SENS_DATA_10 0x53

define EXT_SENS_DATA_11 0x54

define EXT_SENS_DATA_12 0x55

define EXT_SENS_DATA_13 0x56

define EXT_SENS_DATA_14 0x57

define EXT_SENS_DATA_15 0x58

define EXT_SENS_DATA_16 0x59

define EXT_SENS_DATA_17 0x5A

define EXT_SENS_DATA_18 0x5B

define EXT_SENS_DATA_19 0x5C

define EXT_SENS_DATA_20 0x5D

define EXT_SENS_DATA_21 0x5E

define EXT_SENS_DATA_22 0x5F

define EXT_SENS_DATA_23 0x60

define MOT_DETECT_STATUS 0x61

define I2C_SLV0_DO 0x63

define I2C_SLV1_DO 0x64

define I2C_SLV2_DO 0x65

define I2C_SLV3_DO 0x66

define I2C_MST_DELAY_CTRL 0x67

define SIGNAL_PATH_RESET 0x68

define MOT_DETECT_CTRL 0x69

define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP

define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode

define PWR_MGMT_2 0x6C

define DMP_BANK 0x6D // Activates a specific bank in the DMP

define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start address in specified DMP bank

define DMP_REG 0x6F // Register in DMP from which to read or to which to write

define DMP_REG_1 0x70

define DMP_REG_2 0x71

define FIFO_COUNTH 0x72

define FIFO_COUNTL 0x73

define FIFO_R_W 0x74

define WHO_AM_I_MPU9250 0x75 // Should return 0x71

define XA_OFFSET_H 0x77

define XA_OFFSET_L 0x78

define YA_OFFSET_H 0x7A

define YA_OFFSET_L 0x7B

define ZA_OFFSET_H 0x7D

define ZA_OFFSET_L 0x7E

// Using the MSENSR-9250 breakout board, ADO is set to 0
// Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1

define ADO 1

if ADO

define MPU9250_ADDRESS 0x69 // Device address when ADO = 1

else

define MPU9250_ADDRESS 0x68 // Device address when ADO = 0

define AK8963_ADDRESS 0x0C // Address of magnetometer

endif

define AHRS true // set to false for basic data read

define SerialDebug true // set to true to get Serial output for debugging

// Set initial input parameters
enum Ascale {
AFS_2G = 0,
AFS_4G,
AFS_8G,
AFS_16G
};

enum Gscale {
GFS_250DPS = 0,
GFS_500DPS,
GFS_1000DPS,
GFS_2000DPS
};

enum Mscale {
MFS_14BITS = 0, // 0.6 mG per LSB
MFS_16BITS // 0.15 mG per LSB
};

// Specify sensor full scale
uint8_t Gscale = GFS_250DPS;
uint8_t Ascale = AFS_2G;
uint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer resolution
uint8_t Mmode = 0x02; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read
float aRes, gRes, mRes; // scale resolutions per LSB for the sensors

// Pin definitions
int intPin = 12; // These can be changed, 2 and 3 are the Arduinos ext int pins
int myLed = 13; // Set up pin 13 led for toggling

int16_t accelCount[3]; // Stores the 16-bit signed accelerometer sensor output
int16_t gyroCount[3]; // Stores the 16-bit signed gyro sensor output
int16_t magCount[3]; // Stores the 16-bit signed magnetometer sensor output
float magCalibration[3] = {0, 0, 0}, magbias[3] = {0, 0, 0}; // Factory mag calibration and mag bias
float gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}; // Bias corrections for gyro and accelerometer
int16_t tempCount; // temperature raw count output
float temperature; // Stores the real internal chip temperature in degrees Celsius
float SelfTest[6]; // holds results of gyro and accelerometer self test

// global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
// There is a tradeoff in the beta parameter between accuracy and response speed.
// In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.
// However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.
// Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!
// By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec
// I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense;
// the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy.
// In any case, this is the free parameter in the Madgwick filtering and fusion scheme.
float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta
float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value

define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral

define Ki 0.0f

uint32_t delt_t = 0; // used to control display output rate
uint32_t count = 0, sumCount = 0; // used to control display output rate
float pitch, yaw, roll;
float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t Now = 0; // used to calculate integration interval

float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values
float q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion
float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Implementation of Sebastian Madgwick's "...efficient orientation filter for... inertial/magnetic sensor arrays"
// (see http://www.x-io.co.uk/category/open-source/ for examples and more details)
// which fuses acceleration, rotation rate, and magnetic moments to produce a quaternion-based estimate of absolute
// device orientation -- which can be converted to yaw, pitch, and roll. Useful for stabilizing quadcopters, etc.
// The performance of the orientation filter is at least as good as conventional Kalman-based filtering algorithms
// but is much less computationally intensive---it can be performed on a 3.3 V Pro Mini operating at 8 MHz!
void MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;

        // Auxiliary variables to avoid repeated arithmetic
        float _2q1mx;
        float _2q1my;
        float _2q1mz;
        float _2q2mx;
        float _4bx;
        float _4bz;
        float _2q1 = 2.0f * q1;
        float _2q2 = 2.0f * q2;
        float _2q3 = 2.0f * q3;
        float _2q4 = 2.0f * q4;
        float _2q1q3 = 2.0f * q1 * q3;
        float _2q3q4 = 2.0f * q3 * q4;
        float q1q1 = q1 * q1;
        float q1q2 = q1 * q2;
        float q1q3 = q1 * q3;
        float q1q4 = q1 * q4;
        float q2q2 = q2 * q2;
        float q2q3 = q2 * q3;
        float q2q4 = q2 * q4;
        float q3q3 = q3 * q3;
        float q3q4 = q3 * q4;
        float q4q4 = q4 * q4;

        // Normalise accelerometer measurement
        norm = sqrt(ax * ax + ay * ay + az * az);
        if (norm == 0.0f) return; // handle NaN
        norm = 1.0f/norm;
        ax *= norm;
        ay *= norm;
        az *= norm;

        // Normalise magnetometer measurement
        norm = sqrt(mx * mx + my * my + mz * mz);
        if (norm == 0.0f) return; // handle NaN
        norm = 1.0f/norm;
        mx *= norm;
        my *= norm;
        mz *= norm;

        // Reference direction of Earth's magnetic field
        _2q1mx = 2.0f * q1 * mx;
        _2q1my = 2.0f * q1 * my;
        _2q1mz = 2.0f * q1 * mz;
        _2q2mx = 2.0f * q2 * mx;
        hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
        hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
        _2bx = sqrt(hx * hx + hy * hy);
        _2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
        _4bx = 2.0f * _2bx;
        _4bz = 2.0f * _2bz;

        // Gradient decent algorithm corrective step
        s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
        s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
        s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
        s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
        norm = sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4);    // normalise step magnitude
        norm = 1.0f/norm;
        s1 *= norm;
        s2 *= norm;
        s3 *= norm;
        s4 *= norm;

        // Compute rate of change of quaternion
        qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
        qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
        qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
        qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;

        // Integrate to yield quaternion
        q1 += qDot1 * deltat;
        q2 += qDot2 * deltat;
        q3 += qDot3 * deltat;
        q4 += qDot4 * deltat;
        norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);    // normalise quaternion
        norm = 1.0f/norm;
        q[0] = q1 * norm;
        q[1] = q2 * norm;
        q[2] = q3 * norm;
        q[3] = q4 * norm;

    }

// Similar to Madgwick scheme but uses proportional and integral filtering on the error between estimated reference vectors and
// measured ones.
void MahonyQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;

        // Auxiliary variables to avoid repeated arithmetic
        float q1q1 = q1 * q1;
        float q1q2 = q1 * q2;
        float q1q3 = q1 * q3;
        float q1q4 = q1 * q4;
        float q2q2 = q2 * q2;
        float q2q3 = q2 * q3;
        float q2q4 = q2 * q4;
        float q3q3 = q3 * q3;
        float q3q4 = q3 * q4;
        float q4q4 = q4 * q4;   

        // Normalise accelerometer measurement
        norm = sqrt(ax * ax + ay * ay + az * az);
        if (norm == 0.0f) return; // handle NaN
        norm = 1.0f / norm;        // use reciprocal for division
        ax *= norm;
        ay *= norm;
        az *= norm;

        // Normalise magnetometer measurement
        norm = sqrt(mx * mx + my * my + mz * mz);
        if (norm == 0.0f) return; // handle NaN
        norm = 1.0f / norm;        // use reciprocal for division
        mx *= norm;
        my *= norm;
        mz *= norm;

        // Reference direction of Earth's magnetic field
        hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
        hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
        bx = sqrt((hx * hx) + (hy * hy));
        bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);

        // Estimated direction of gravity and magnetic field
        vx = 2.0f * (q2q4 - q1q3);
        vy = 2.0f * (q1q2 + q3q4);
        vz = q1q1 - q2q2 - q3q3 + q4q4;
        wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
        wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
        wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);  

        // Error is cross product between estimated direction and measured direction of gravity
        ex = (ay * vz - az * vy) + (my * wz - mz * wy);
        ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
        ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
        if (Ki > 0.0f)
        {
            eInt[0] += ex;      // accumulate integral error
            eInt[1] += ey;
            eInt[2] += ez;
        }
        else
        {
            eInt[0] = 0.0f;     // prevent integral wind up
            eInt[1] = 0.0f;
            eInt[2] = 0.0f;
        }

        // Apply feedback terms
        gx = gx + Kp * ex + Ki * eInt[0];
        gy = gy + Kp * ey + Ki * eInt[1];
        gz = gz + Kp * ez + Ki * eInt[2];

        // Integrate rate of change of quaternion
        pa = q2;
        pb = q3;
        pc = q4;
        q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);
        q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);
        q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);
        q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);

        // Normalise quaternion
        norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
        norm = 1.0f / norm;
        q[0] = q1 * norm;
        q[1] = q2 * norm;
        q[2] = q3 * norm;
        q[3] = q4 * norm;

    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void setup()
{
//Wire.begin();
// TWBR = 12; // 400 kbit/sec I2C speed
Serial.begin(38400);

// Set up the interrupt pin, its set as active high, push-pull
pinMode(intPin, INPUT);
digitalWrite(intPin, LOW);
pinMode(myLed, OUTPUT);
digitalWrite(myLed, HIGH);

delay(1000);

// Read the WHO_AM_I register, this is a good test of communication
//byte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I register for MPU-9250
//Serial.print("MPU9250 "); Serial.print("I AM "); Serial.print(c, HEX); Serial.print(" I should be "); Serial.println(0x71, HEX);

byte id;

Serial.begin( 115200 );

pinMode( NCS_PIN, OUTPUT );
pinMode( MOSI_PIN, OUTPUT );
pinMode( MISO_PIN, INPUT );
pinMode( SCK_PIN, OUTPUT );

SPI.begin( );
SPI.setDataMode( SPI_MODE3 );
SPI.setBitOrder( MSBFIRST );
SPI.setClockDivider( 16 ); // 1MHz
digitalWrite(NCS, HIGH);
delay( 1000 );

Serial.println( "MPU9250 SPI" );

// reset the device
SPI_write_register( 0x6B, 0x80 );
delay( 100 );

// disable I2C protocol
SPI_write_register( 0x6A, 0x10 );
delay( 100 );

// reset acc, gyro and temp
SPI_write_register( 0x68, 0x07 );
delay( 100 );

if(SPI_read_register(0x75) == 0x71)
{
Serial.println("MPU9250 is online...");

MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values
Serial.print("x-axis self test: acceleration trim within : "); Serial.print(SelfTest[0],1); Serial.println("% of factory value");
Serial.print("y-axis self test: acceleration trim within : "); Serial.print(SelfTest[1],1); Serial.println("% of factory value");
Serial.print("z-axis self test: acceleration trim within : "); Serial.print(SelfTest[2],1); Serial.println("% of factory value");
Serial.print("x-axis self test: gyration trim within : "); Serial.print(SelfTest[3],1); Serial.println("% of factory value");
Serial.print("y-axis self test: gyration trim within : "); Serial.print(SelfTest[4],1); Serial.println("% of factory value");
Serial.print("z-axis self test: gyration trim within : "); Serial.print(SelfTest[5],1); Serial.println("% of factory value");

calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers

delay(1000); 

initMPU9250(); 
Serial.println("MPU9250 initialized for active data mode...."); // Initialize device for active mode read of acclerometer, gyroscope, and temperature

// Read the WHO_AM_I register of the magnetometer, this is a good test of communication
byte d = readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);  // Read WHO_AM_I register for AK8963
Serial.print("AK8963 "); Serial.print("I AM "); Serial.print(d, HEX); Serial.print(" I should be "); Serial.println(0x48, HEX);

delay(1000); 

// Get magnetometer calibration from AK8963 ROM
initAK8963(magCalibration); Serial.println("AK8963 initialized for active data mode...."); // Initialize device for active mode read of magnetometer

if(SerialDebug) {
// Serial.println("Calibration values: ");
Serial.print("X-Axis sensitivity adjustment value "); Serial.println(magCalibration[0], 2);
Serial.print("Y-Axis sensitivity adjustment value "); Serial.println(magCalibration[1], 2);
Serial.print("Z-Axis sensitivity adjustment value "); Serial.println(magCalibration[2], 2);
}

delay(1000);  

}
else
{
Serial.print("Could not connect to MPU9250");
while(1) ; // Loop forever if communication doesn't happen
}
}

void loop()
{
// If intPin goes high, all data registers have new data
if (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) { // On interrupt, check if data ready interrupt
readAccelData(accelCount); // Read the x/y/z adc values
getAres();

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

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

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

readMagData(magCount);  // Read the x/y/z adc values
getMres();
magbias[0] = +470.;  // User environmental x-axis correction in milliGauss, should be automatically calculated
magbias[1] = +120.;  // User environmental x-axis correction in milliGauss
magbias[2] = +125.;  // User environmental x-axis correction in milliGauss

// Calculate the magnetometer values in milliGauss
// Include factory calibration per data sheet and user environmental corrections
mx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0];  // get actual magnetometer value, this depends on scale being set
my = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];  
mz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2];   

}

Now = micros();
deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
lastUpdate = Now;

sum += deltat; // sum for averaging filter update rate
sumCount++;

// Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer;
// the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of accelerometer and gyro!
// We have to make some allowance for this orientationmismatch in feeding the output to the quaternion filter.
// For the MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like
// in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention.
// This is ok by aircraft orientation standards!
// Pass gyro rate as rad/s
// MadgwickQuaternionUpdate(ax, ay, az, gx_PI/180.0f, gy_PI/180.0f, gz_PI/180.0f, my, mx, mz);
MahonyQuaternionUpdate(ax, ay, az, gx_PI/180.0f, gy_PI/180.0f, gz_PI/180.0f, my, mx, mz);

if (!AHRS) {
delt_t = millis() - count;
if(delt_t > 500) {

if(SerialDebug) {
// Print acceleration values in milligs!
Serial.print("X-acceleration: "); Serial.print(1000*ax); Serial.print(" mg ");
Serial.print("Y-acceleration: "); Serial.print(1000*ay); Serial.print(" mg ");
Serial.print("Z-acceleration: "); Serial.print(1000*az); Serial.println(" mg ");

// Print gyro values in degree/sec
Serial.print("X-gyro rate: "); Serial.print(gx, 3); Serial.print(" degrees/sec "); 
Serial.print("Y-gyro rate: "); Serial.print(gy, 3); Serial.print(" degrees/sec "); 
Serial.print("Z-gyro rate: "); Serial.print(gz, 3); Serial.println(" degrees/sec"); 

// Print mag values in degree/sec
Serial.print("X-mag field: "); Serial.print(mx); Serial.print(" mG "); 
Serial.print("Y-mag field: "); Serial.print(my); Serial.print(" mG "); 
Serial.print("Z-mag field: "); Serial.print(mz); Serial.println(" mG"); 

tempCount = readTempData();  // Read the adc values
temperature = ((float) tempCount) / 333.87 + 21.0; // Temperature in degrees Centigrade

// Print temperature in degrees Centigrade
Serial.print("Temperature is "); Serial.print(temperature, 1); Serial.println(" degrees C"); // Print T values to tenths of s degree C
}

count = millis();
digitalWrite(myLed, !digitalRead(myLed));  // toggle led
}
}
else {

// Serial print and/or display at 0.5 s rate independent of data rates
delt_t = millis() - count;
if (delt_t > 500) { // update LCD once per half-second independent of read rate

if(SerialDebug) {
Serial.print("ax = "); Serial.print((int)1000*ax);  
Serial.print(" ay = "); Serial.print((int)1000*ay); 
Serial.print(" az = "); Serial.print((int)1000*az); Serial.println(" mg");
Serial.print("gx = "); Serial.print( gx, 2); 
Serial.print(" gy = "); Serial.print( gy, 2); 
Serial.print(" gz = "); Serial.print( gz, 2); Serial.println(" deg/s");
Serial.print("mx = "); Serial.print( (int)mx ); 
Serial.print(" my = "); Serial.print( (int)my ); 
Serial.print(" mz = "); Serial.print( (int)mz ); Serial.println(" mG");

Serial.print("q0 = "); Serial.print(q[0]);
Serial.print(" qx = "); Serial.print(q[1]); 
Serial.print(" qy = "); Serial.print(q[2]); 
Serial.print(" qz = "); Serial.println(q[3]); 
}               

// Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.
// In this coordinate system, the positive z-axis is down toward Earth.
// Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
// Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
// Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
// These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
// Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
// applied in the correct order which for this configuration is yaw, pitch, and then roll.
// For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
yaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
roll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
pitch *= 180.0f / PI;
yaw *= 180.0f / PI;
yaw -= 13.8; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
roll *= 180.0f / PI;

if(SerialDebug) {
Serial.print("Yaw, Pitch, Roll: ");
Serial.print(yaw, 2);
Serial.print(", ");
Serial.print(pitch, 2);
Serial.print(", ");
Serial.println(roll, 2);

Serial.print("rate = "); Serial.print((float)sumCount/sum, 2); Serial.println(" Hz");
}



// With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and 
// >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz.
// The filter update rate is determined mostly by the mathematical steps in the respective algorithms, 
// the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR:
// an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces
// filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively. 
// This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads.
// This filter update rate should be fast enough to maintain accurate platform orientation for 
// stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz
// produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors.
// The 3.3 V 8 MHz Pro Mini is doing pretty well!


count = millis(); 
sumCount = 0;
sum = 0;    
}
}

}

//===================================================================================================================
//====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data
//===================================================================================================================

void getMres() {
switch (Mscale)
{
// Possible magnetometer scales (and their register bit settings) are:
// 14 bit resolution (0) and 16 bit resolution (1)
case MFS_14BITS:
mRes = 10._4912./8190.; // Proper scale to return milliGauss
break;
case MFS_16BITS:
mRes = 10._4912./32760.0; // Proper scale to return milliGauss
break;
}
}

void getGres() {
switch (Gscale)
{
// Possible gyro scales (and their register bit settings) are:
// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case GFS_250DPS:
gRes = 250.0/32768.0;
break;
case GFS_500DPS:
gRes = 500.0/32768.0;
break;
case GFS_1000DPS:
gRes = 1000.0/32768.0;
break;
case GFS_2000DPS:
gRes = 2000.0/32768.0;
break;
}
}

void getAres() {
switch (Ascale)
{
// Possible accelerometer scales (and their register bit settings) are:
// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case AFS_2G:
aRes = 2.0/32768.0;
break;
case AFS_4G:
aRes = 4.0/32768.0;
break;
case AFS_8G:
aRes = 8.0/32768.0;
break;
case AFS_16G:
aRes = 16.0/32768.0;
break;
}
}

void readAccelData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z accel register data stored here
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}

void readGyroData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}

void readMagData(int16_t * destination)
{
uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition
if(readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01) { // wait for magnetometer data ready bit to be set
readBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]); // Read the six raw data and ST2 registers sequentially into data array
uint8_t c = rawData[6]; // End data read by reading ST2 register
if(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then report data
destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as little Endian
destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}
}
}

int16_t readTempData()
{
uint8_t rawData[2]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw data registers sequentially into data array
return ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a 16-bit value
}

void initAK8963(float * destination)
{
// First extract the factory calibration for each magnetometer axis
uint8_t rawData[3]; // x/y/z gyro calibration data stored here
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode
delay(10);
readBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]); // Read the x-, y-, and z-axis calibration values
destination[0] = (float)(rawData[0] - 128)/256. + 1.; // Return x-axis sensitivity adjustment values, etc.
destination[1] = (float)(rawData[1] - 128)/256. + 1.;
destination[2] = (float)(rawData[2] - 128)/256. + 1.;
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
// Configure the magnetometer for continuous read and highest resolution
// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,
// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates
writeByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR
delay(10);
}

void initMPU9250()
{
// wake up device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors
delay(100); // Wait for all registers to reset

// get stable time source
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // Auto select clock source to be PLL gyroscope reference if ready else
delay(200);

// Configure Gyro and Thermometer
// Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
// minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
// be higher than 1 / 0.0059 = 170 Hz
// DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
// With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x03);

// Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; a rate consistent with the filter update rate
// determined inset in CONFIG above

// Set gyroscope full scale range
// Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);
// writeRegister(GYRO_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x02); // Clear Fchoice bits [1:0]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c | Gscale << 3); // Set full scale range for the gyro
// writeRegister(GYRO_CONFIG, c | 0x00); // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG

// Set accelerometer full-scale range configuration
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG);
// writeRegister(ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c | Ascale << 3); // Set full scale range for the accelerometer

// Set accelerometer sample rate configuration
// It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for
// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2);
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c & ~0x0F); // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c | 0x03); // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz

// The accelerometer, gyro, and thermometer are set to 1 kHz sample rates,
// but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting

// Configure Interrupts and Bypass Enable
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips
// can join the I2C bus and all can be controlled by the Arduino as master
writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22);
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt
delay(100);
}

// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
void calibrateMPU9250(float * dest1, float * dest2)
{
uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data
uint16_t ii, packet_count, fifo_count;
int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0};

// reset device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
delay(100);

// get stable time source; Auto select clock source to be PLL gyroscope reference if ready
// else use the internal oscillator, bits 2:0 = 001
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
writeByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);
delay(200);

// Configure device for bias calculation
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source
writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP
delay(15);

// Configure MPU6050 gyro and accelerometer for bias calculation
writeByte(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity

uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec
uint16_t accelsensitivity = 16384; // = 16384 LSB/g

// Configure FIFO to capture accelerometer and gyro data for bias calculation

writeByte(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 512 bytes in MPU-9150)
delay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes

// At end of sample accumulation, turn off FIFO sensor read
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer sensors for FIFO
readBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count
fifo_count = ((uint16_t)data[0] << 8) | data[1];
packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging

for (ii = 0; ii < packet_count; ii++) {
int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};
readBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging
accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form signed 16-bit integer for each sample in FIFO
accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ;
accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ;
gyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ;
gyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ;
gyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;

accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases
accel_bias[1] += (int32_t) accel_temp[1];
accel_bias[2] += (int32_t) accel_temp[2];
gyro_bias[0]  += (int32_t) gyro_temp[0];
gyro_bias[1]  += (int32_t) gyro_temp[1];
gyro_bias[2]  += (int32_t) gyro_temp[2];

}
accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases
accel_bias[1] /= (int32_t) packet_count;
accel_bias[2] /= (int32_t) packet_count;
gyro_bias[0] /= (int32_t) packet_count;
gyro_bias[1] /= (int32_t) packet_count;
gyro_bias[2] /= (int32_t) packet_count;

if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} // Remove gravity from the z-axis accelerometer bias calculation
else {accel_bias[2] += (int32_t) accelsensitivity;}

// Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup
data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format
data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases
data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;
data[3] = (-gyro_bias[1]/4) & 0xFF;
data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;
data[5] = (-gyro_bias[2]/4) & 0xFF;

// Push gyro biases to hardware registers
writeByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);
writeByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);

// Output scaled gyro biases for display in the main program
dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;
dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;
dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;

// Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain
// factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold
// non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature
// compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that
// the accelerometer biases calculated above must be divided by 8.

int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases
readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values
accel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]);
accel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]);
accel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]);

uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers
uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis

for(ii = 0; ii < 3; ii++) {
if((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit
}

// Construct total accelerometer bias, including calculated average accelerometer bias from above
accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg[1] -= (accel_bias[1]/8);
accel_bias_reg[2] -= (accel_bias[2]/8);

data[0] = (accel_bias_reg[0] >> 8) & 0xFF;
data[1] = (accel_bias_reg[0]) & 0xFF;
data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[2] = (accel_bias_reg[1] >> 8) & 0xFF;
data[3] = (accel_bias_reg[1]) & 0xFF;
data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[4] = (accel_bias_reg[2] >> 8) & 0xFF;
data[5] = (accel_bias_reg[2]) & 0xFF;
data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers

// Apparently this is not working for the acceleration biases in the MPU-9250
// Are we handling the temperature correction bit properly?
// Push accelerometer biases to hardware registers
writeByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);
writeByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);
writeByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);
writeByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);
writeByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);
writeByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);

// Output scaled accelerometer biases for display in the main program
dest2[0] = (float)accel_bias[0]/(float)accelsensitivity;
dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;
dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;
}

// Accelerometer and gyroscope self test; check calibration wrt factory settings
void MPU9250SelfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass
{
uint8_t rawData[6] = {0, 0, 0, 0, 0, 0};
uint8_t selfTest[6];
int16_t gAvg[3], aAvg[3], aSTAvg[3], gSTAvg[3];
float factoryTrim[6];
uint8_t FS = 0;

writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz and DLPF to 92 Hz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 1<<FS); // Set full scale range for the gyro to 250 dps
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 1<<FS); // Set full scale range for the accelerometer to 2 g

for( int ii = 0; ii < 200; ii++) { // get average current values of gyro and acclerometer

readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;

readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);       // Read the six raw data registers sequentially into data array

gAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}

for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average current readings
aAvg[ii] /= 200;
gAvg[ii] /= 200;
}

// Configure the accelerometer for self-test
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s
delay(25); // Delay a while to let the device stabilize

for( int ii = 0; ii < 200; ii++) { // get average self-test values of gyro and acclerometer

readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;

readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array

gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}

for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average self-test readings
aSTAvg[ii] /= 200;
gSTAvg[ii] /= 200;
}

// Configure the gyro and accelerometer for normal operation
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);
delay(25); // Delay a while to let the device stabilize

// Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg
selfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel self-test results
selfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel self-test results
selfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel self-test results
selfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO); // X-axis gyro self-test results
selfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO); // Y-axis gyro self-test results
selfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO); // Z-axis gyro self-test results

// Retrieve factory self-test value from self-test code reads
factoryTrim[0] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[0] - 1.0) )); // FT[Xa] factory trim calculation
factoryTrim[1] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[1] - 1.0) )); // FT[Ya] factory trim calculation
factoryTrim[2] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[2] - 1.0) )); // FT[Za] factory trim calculation
factoryTrim[3] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[3] - 1.0) )); // FT[Xg] factory trim calculation
factoryTrim[4] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[4] - 1.0) )); // FT[Yg] factory trim calculation
factoryTrim[5] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[5] - 1.0) )); // FT[Zg] factory trim calculation

// Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response
// To get percent, must multiply by 100
for (int i = 0; i < 3; i++) {
destination[i] = 100.0_((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i]; // Report percent differences
destination[i+3] = 100.0_((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3]; // Report percent differences
}

}

void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
SPI_write_register( subAddress, data );
}

uint8_t readByte(uint8_t address, uint8_t subAddress)
{
uint8_t data; // data will store the register data
data = SPI_read_register( subAddress );
return data; // Return data read from slave register
}

void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{

digitalWrite( NCS, LOW);

for (int i = 0; i < count; ++i)
{
uint8_t reg = subAddress + i;
SPI.transfer( reg | 0x80 ); // reg | 0x80 to denote read
uint8_t read_value = SPI.transfer( 0x00 ); // write 8-bits zero
dest[i] = read_value;
}
digitalWrite( NCS, HIGH);
}

accelerometer and magnetometer orientation

Hello! I have a few question to your MPU9250BasicAHRS.ino file.

// Sensors x (y) -axis of the accelerometer is aligned with the y (x) -axis of the magnetometer; // The z-axis magnetometer (+ Down) is opposite to the z-axis (+ up) of accelerometer and gyro! // We have to make some allowance for this orientationmismatch in feeding the output to the quaternion filter. // For the MPU-9250, we have chosen a magnetic rotation sensor That keeps the forwards along the x-axis just like // in the LSM9DS0 sensor. This rotation can be modified is allow any convenient orientation convention. // This is ok to aircraft orientation standards! // Pass rate gyro as rad / s
// Madgwick Quaternion Update (ax, ay, az, GX * PI / 180.0f, gy * PI / 180.0f, g * PI / 180.0f, we, x, m); Mahony Quaternion Update (ax, ay, az, GX * PI / 180.0f, gy * PI / 180.0f, g * PI / 180.0f, we, x, m);

1.Why you did not use -mz instead of mz? I mean
MahonyQuaternionUpdate (ax, ay, az, GX * PI / 180.0f, gy * PI / 180.0f, g * PI / 180.0f, my mx -mz);
Why in your code mz is positive?
2. Is it necessary that calculate mx,my,mz is gauss? In the filter is normalized it anyway? Or I am wrong?

DMP Usage

So internal to the MPU-xxxx IMUs, there is this mystical "Digital Motion Processing" unit that does some sensor fusion. I looked through the code and didn't notice it being used. Supposedly it would take out a lot of the pain of doing sensor fusion. Is it due to lack of documentation on the "DMP" unit or why is it you go about getting the raw values then performing your own calculations on them?

WHO_AM_I reads, compass doesn't


MPU9250 I AM 71 I should be 71
MPU9250 is online...
x-axis self test: acceleration trim within : -0.4% of factory value
y-axis self test: acceleration trim within : -0.2% of factory value
z-axis self test: acceleration trim within : 0.2% of factory value
x-axis self test: gyration trim within : -0.1% of factory value
y-axis self test: gyration trim within : -0.1% of factory value
z-axis self test: gyration trim within : 0.2% of factory value
MPU9250 initialized for active data mode....
AK8963 I AM FF I should be 48
AK8963 initialized for active data mode....
X-Axis sensitivity adjustment value 1.26
Y-Axis sensitivity adjustment value 0.52
Z-Axis sensitivity adjustment value 0.94
ax = 37.35 ay = 37.29 az = 37.23 mg
gx = 4.26 gy = 4.25 gz = 4.24 deg/s
mx = -470 my = -120 mz = -125 mG
q0 = 1.00 qx = 0.00 qy = 0.00 qz = 0.00
Yaw, Pitch, Roll: -13.80, 0.00, 0.00
rate = 0.56 Hz
ax = 37.35 ay = 37.29 az = 37.23 mg
gx = 4.26 gy = 4.25 gz = 4.24 deg/s
mx = 16961 my = -120 mz = -122 mG
q0 = 1.00 qx = 0.00 qy = 0.00 qz = 0.00
Yaw, Pitch, Roll: -13.80, 0.00, 0.00
rate = 602.14 Hz

None of these values change when I move the chip.


 // Configure Interrupts and Bypass Enable 
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared, 
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips 
// can join the I2C bus and all can be controlled by the Arduino as master writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22); 
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01);  // Enable data ready (bit 0) interrupt

is set, so it should be in bypass mode and the compass WHO_AM_I register should read, right? This might be entirely a hardware problem.

Multiple I2C with MPU9250

Hi...
How can I change the code to connect at least 2 MPU9250 sensor to STM32F401RE to different I2C buses

Device doesn't seems to be working properly.

I have this board: http://www.embeddedmasters.com/PortalProductDetail.aspx?ProdId=552444#.VHidcTHF-os
So far I have made attempts to initialize based on my personal understanding of the datasheet. As the result I'm successfully reading WhoAmI register and accelerometr output registers. The issue that AX, AY an AZ do not change at all except after reset...Reading configuration registers back doesn't make sense - all 0.
The second attempt was to use other initialization routines found on the web. Basically the same result.
The third was porting this code. No luck.

Any suggestions?

Thanks.

Register setup error?

Hi Kris,

I'm using your MPU9250 code with a Teensy 3.2 and it has been a vast help to me, thank you very much for making it available. However, there seems to be a flaw in the code that sets up some of the configuration registers. In initMPU9250() you have code intended to read, modify and write back register data thus:

// Set gyroscope full scale range
// Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x02); // Clear Fchoice bits [1:0]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c | Gscale << 3); // Set full scale range for the gyro

but surely this is not correct? Each time you write to the register you overwrite whatever you wrote before, so the fchoice selection is unchanged and the full-scale selects are or-ed with the previous values (I found this when I tried to use different scale values). I think the code needs to be something like:

uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);
c &= ~0x02; // Clear Fchoice bits [1:0](but I think it should be ~0x03)
c &= ~0x18; // Clear AFS bits [4:3]
c |= Gscale << 3; // Set full scale range for the gyro
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c); // Write back changed data

The same issue applies to setting up ACCEL_CONFIG and ACCEL_CONFIG2.

My apologies if I should have submitted changed code to the repository instead of bothering you - I'm very new to GitHub.

Accerometer Offset Issues

Many thanks for sharing your code!
Porting code to the MK22FN512 & Kinetis studios.
Having accelerometer/gryo offset issues. Startup Offsets are not correctly removed.
Using https://github.com/kriswiner/MPU-9250/blob/master/MPU9250BasicAHRS_t3.ino as reference. (could not find a read-me of what each file is, hopefully this one is OK).
Here is my startup printout (slightly modified from original code):
Image of Startupt

Those offsets are not correctly removed so my normal accelerometer output is
-1g , 0g, 2g

I noticed the code comment "
// Apparently this is not working for the acceleration biases in the MPU-9250
// Are we handling the temperature correction bit properly?
// Push accelerometer biases to hardware registers "

as well as in the loop code
// Now we'll calculate the accleration value into actual g's
ax = (float)accelCount[0]_aRes; // - accelBias[0]; // get actual g value, this depends on scale being set
ay = (float)accelCount[1]_aRes; // - accelBias[1];
az = (float)accelCount[2]*aRes; // - accelBias[2];

Looks like at one point the acc bias dirtly applied directly to the output. I'm guessing if I did that i'd get the correct result. Anyone have any ideas? Going to look through the other code bases & see if the offset code is different in those. Any ideas would be awesome!
Thanks,
-Nate

EMSENSR-MPU9250 burning up/shorting randomly (Teensy 3.1)

Guys,
I've been running Teensy 3.1 connected to an EMSENSR-MPU9250 successfully, however after 2-8 hours of operation the 9250 breakout board is burning up and shorting VDDIO to GND, and then burning up my Teensy 3.1.

I've contacted the embedded masters (mfg of EMSENSR-MPU9250) with little success. I wanted to make sure that my wiring was correct, or if anyone else was having this issue?

Teensy 3.1 -------------- EMSENSR-MPU9250
3.3V ----------------------- VDD
3.3V ----------------------- VDDIO
GND ----------------------- GND
SDA0 (PIN 18)------------ SDA
SCL0 (PIN 19)------------ SCL

I have been using the pullup resistors built into 9250 Breakout board, and haven't added any other resistors to my system.

Again, I've been able to communicate with the 9250's successfully for anywhere from 2-8 hours, but sometime in that window I've been experiencing the short and burn-up glitch.

Anyone have any insight or ideas?

Thanks for the help!

-Corbin

Sketch issues and mag issue

I came across your sketch while looking for a solution to not being able to read or see the magnetometer. Saw that you have to read 7 bytesinstead of 6 as on the 9150 and figure I would give your sketch a try before I did anything else. Anyway came across two things: (1) think you need to include the madgwickahrsupdate code or it will not work and (2) which is my problem the sketch returns FF instead of 48 when it does a whoiam on the ako8963. Any thoughts on what the problem could be?

I did go through the possible magazine addresses just in case and when I run a i2cscanner the only thing I see is the 9250 address which reads fine. The only thing incandescent think of is that it is a bad chip or they put a 6050 on the board instead of the 9250.

Ground plane under the chip

Hello kriswiner,

I find all your MPU-9250 board were designed without ground plane under the chip. In datasheet of MPU-9150, the Assembly Precautions section point out

The exposed center die pad(e-pad or thermal pad) is not required for heat sinking, and should not be soldered to the PCB.

But it also point out

For best performance, design a ground plane under the e-pad to reduce PCB signal noise from the board on which the gyro device is mounted. If the gyro device is stacked under an adjacent PCB board, design a ground plane directly above the gyro device to shield active signals from the adjacent PCB board.

Does it mean a ground plane under the e-pad is necessary but should not be soldered to the e-pad?

I recently contacted Invensense, they said the same design rules are still applicable to MPU-9250. Your mini MPU9250 Teensy 3.1 add-on shields are directly mounted under Teensy board. If without a ground plane between Teensy and MPU9250, would the performance of gyro in MPU9250 affected by Teensy board?

Thanks

Joint angle calculation

I want to attach the 9-axis imu on finger to calculate the joint angles. I have used Madgwick Algorithm and got the quaternion of imu after each update. I know the quaternion can show the attitude of each sensor's rotation without gimbal lock, but how can I calculate and show the angle between two imu? When my hand back is toward up, I can simply use the difference between euler angles of two imu.(roll of imu1 - roll of imu2) However, when my hand back toward left or right, I can not get the correct angle. Do you have any ideas about solving this problem? Thank you very much.

Magnetometer calibration and differents issues

Hi Kris,
I'm trying to run the AHRS with the new NUCLEO cortex M7.
The fusion rate is around 8000Hz.
But I'm still not able to get any results usable.
I calibrated the magnetometer with your magCalibration+ magScale, but I don't understand when I plot my sphere, the resultat is not well centred as you can see:
spheremag
I'm in 8Hz magneto rate.
So It results that the pitch and roll seems correct but the yaw is never correct. During the calibration you said to wawe the device in a figure eight until done, this means that the MPU9250 should lay flat on the table?
At the begining I thought It was my µC which was not enough fast for the fusion, but now with the cortexM7 it's couldn't be that, so what do you suggest?
It's hard to believe this algo could be run for a camera stabilization, when there is an acceleration on axe X, Y or Z the angles changes or swing, is that the same for you?

Thank you very much Kris

calibration of magnetometer

Hello kriswiner,
I read you article: https://github.com/kriswiner/MPU-6050/wiki/Simple-and-Effective-Magnetometer-Calibration and I am wondering about a few things:
. do you know if in the Android OS this calibration is included or does the App writers need to implement this?
. if it is part of the OS, is this 'calibration' movement one need to do in some way recognised by the OS? And when recognised, it performs the calibration (both for hard and soft irons?).

I am asking this as I have some problems with measuring azi/alt.
I am using a Samsung Tab2 7.0 GT-P3110 Android 4.2.2
Regardless of the App I am using (e.g. SunSurveyor or Measure Angle/Geosurvey Transit Apps), the results of azimuth and altitude measurements depend on the rotation of the device. So when pointing towards an object (Moon/Sun) with known azi/alt with the camera, the azimuth and altitude measurements changes when the device is rotated (see attached plot).
image18

The precision both in azimuth and altitude is quite good (0.5 deg, by measuring the azi/alt several times using the same rotation of the device), which is close to the one of a normal compass/clinometer. But the accuracy is not that good!
<see for definition of the word accuracy and precision here: https://en.wikipedia.org/wiki/Accuracy_and_precision >

Attached is a plot of the measured azi and alt (using SunSurveyor App,
but other Apps [such as Measure Angle] have same behavior).
I turned the device 90 degrees (starting with landscape, portrait, the
-landscape and -portrait) and measured each time the az/alt of the
Moon. You also see the average of these measurements and the ephemeris location
of the Moon. So the average looks ok-ish compared to
the ephemeris values calculated for the Moon.

I have now been measuring the Moon and Sun many times and I see every
time the similar behavior and accuracy spread (although same variation
can happen). Again the precision stays within the 0.5 degrees when doing
multiple measured at the same rotation.
By the way I am away from iron objects (external or on body) and also
away from electricity cables, etc. I also do the so called
'calibration' of the magnetometer (I did several different calibration
movements). That calibration has some effect, but normally the spread stays the same.
I also compared it with a normal compass and clinometer, which gives values comparable to the ephemeris.

If you see that plot, do you think this is something in the OS, the sensor, the device and/or the App?
Calculating azi/alt is of course not an easy thing. In the device or Operating systems things are being done of course, but I am wondering why I see this large inaccuracy (certainly in azi [up to 20 degrees], and smaller in alt [up to 7 degrees])?

Here is another article that described the issues around the magnetometer
(and also how to overcome them [partly]). I am wondering if the
calibration inside the device and/or OS is done properly?
http://www.nxp.com/files/sensors/doc/app_note/AN4246.pdf

Any ideas/hint you see in this?

Thanks for any feedback.

All the best,

Victor

Arduino Pro Mini

Hallo,
i have an Arduino Pro Mini, MPU-9250 Board and Nokia 5110 Display, but the code works only without serial debug.

Accelerometer/ Trinket

Hey Kris,

I currently using the MPU-9250 with the 3V pro trinket with the pins properly connected and interrupt connected to 3 (since pin 2 doesnt exist). I am getting a weird output... It performed accurately on the arduino uno but when I tried to use the trinket, the Ax and only Ax reading stay constant. Idk if this is a voltage issue or something but the values go constant.

mpu capture

Any thoughts on what could be causing this?

Question about Yaw heading

Hello Kris,

First of all, excellent job with this software! It's really helpful, but I have some question regarding yaw heading. Whenever I move my IMU to a new direction, yaw represents that value correctly, but after a while it returns to the starting direction.

As an example, suppose every coordinate (yaw, pitch, roll) is 0, 0, 0. If I turn the IMU 90 deg fast to the right, yaw changes to 90, 0, 0, but then it slowly returns to 0, 0, 0. Ok, It works as the needle of a compass, but why doesn't it simply continue to point at 90 deg? Pitch and roll works as expected, but why does that happen to yaw?

I've searched for an answer all over google, and I believe that it may be something simple, but the 'click' in my head did not occur. Could you please help me?

Thanks in advance.
Arthur

Environmental magnetometer values

Hi Kris,

I have been following your work for quite some time now and made a nice smartphone app running a orientation filter simulation. Since I am trying to consider every last tweak in calculating propper results from my MPU9250-tags and to improve my simulation the only thing I cant realy grasp is your environmental correction approach for the magnetometer.

magbias[0] = +470.;  // User environmental x-axis correction in milliGauss, should be automatically calculated
magbias[1] = +120.;  // User environmental x-axis correction in milliGauss
magbias[2] = +125.;  // User environmental x-axis correction in milliGauss

From my understanding its like using the built-in magnetometer of a smartphone, taking a decent magnetometer app, doing the figure-8-calibration and afterwards reading the shown magnetometer values in a static scenario (table edge). Is that correct?

Since you left yourself a comment there to do an automatic integration of that environmental correction, thats what I am trying to achieve now and if you like I would be happy to share my results once it is finished.

Hope you can help me out a little!

Regards

Ray

Unstable output coming from MadgwickQuaternionUpdate

Hey Kris! Very inspiring project you've got going on here, this theory is awesome and your implementation and explanations are spot on.

I have been using the MPU-9250 code with my Arduino UNO connected to a standard MPU-9250 chip via i2c. The raw output coming from the sensor is stable and makes sense (isn't oscillating and without any noticeable drifting). When I route the raw input into the MahonyQuaternionUpdate function I get quite reasonable roll, pitch and yaw data, without substantial drift (although a Gimbal lock often occurs, need to find a way to fix that?). However when I plug the raw data into MadgwickQuaternionUpdate the Euler angles are very unstable, especially the yaw which tends to oscillate from -180 to 180 and then from -180 again.

Have you ever encountered this problem before or know of any reason why this could happen?

yaw, pitch, roll between power cycles

Hello Kris,

Thank you for sharing you very nice project. It's awesome.

I have a question about changing of yaw, pitch, roll values between power cycles.
I'm testing your code with MPU-9250 on Arduino MEGA 2560.
I wanted to check if the values of yaw, pitch, roll kept the same between power cycles, so I pushed the reset button of my MEGA 2560 while reading the three values without moving the sensor. The following numbers are some of the reading in order of yaw, pitch and roll. I picked the lines after the values became stable and two lines just to show normal variations.

...
-61.563 0.277 0.133
-61.469 -0.061 0.038
...

...
-70.416 0.192 -9.999
-70.378 0.113 -10.027
...

...
-55.291 8.587 -8.549
-55.127 8.289 -8.659
...

...
-40.901 8.688 -0.057
-40.719 8.436 -0.257

Because the sensor is laid flat on top of a desk, I think roll and pitch should be close to 0 like the top two lines. But they are not always zero after pushing reset button as you see, and yaw is also changed.

I'm wondering if you have ever seen this problem before.
Could you give me any advice on this problem?

Thank you.

How can I get the bias of Acc and Gyro?

Hello, I would like to ask that how to get the bias of Acc and Gyro? I'm not really sure for that......
I let the IMU be flat on the table with Z-axis toward up, and then I get the average value of 1000 records of Ax, Ay, Az. The value should be 0, 0, 1, but the values I got are -0.2, -0.06, 0.96. Is the bias of Acc 0.2, 0.06, 0.04? So I have to add 0.2, 0.06, 0.04 to all of values of Ax, Ay and Az. Is this right?
Can I use the method to get the bias of Gyro, too? I think it should be 0, 0, 0 deg/sec when it is flat on the table.
Thank you very much!

Right hand rule

Hi kriswiner,

could it be that the mpu9250 does not follow the right hand rule?
Kind regards,

Constantin

pitch, yaw, roll Interrupting each other!

Hi Kris
I am running the attached code on a Teensy3.1 and a cheap MPU9250
(http://www.ebay.com/itm/SPI-IIC-MPU-9250-9-Axis-Attitude-Gyro-Accelerator-Magnetometer-Sensor-Module-/131185485892)

I plotted raw data in Matlab and accelerometer,gyro, and magnetometer are all calibrated, The problem is when I Serial.Print (pitch, yaw, roll) after a certain angle they become unstable and they interfere with each other. I am using madwick algorithm as you can see in my code.

Would you please let me know what is wrong with it?

Thanks
Navid

Here is my Code:

/* MPU9250 Basic Example Code
by: Kris Winer
date: April 1, 2014
license: Beerware - Use this code however you'd like. If you
find it useful you can buy me a beer some time.

Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor,
getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to
allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and
Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1.

SDA and SCL should have external pull-up resistors (to 3.3V).
10k resistors are on the EMSENSR-9250 breakout board.

Hardware setup:
MPU9250 Breakout --------- Arduino
VDD ---------------------- 3.3V
VDDI --------------------- 3.3V
SDA ----------------------- A4
SCL ----------------------- A5
GND ---------------------- GND

Note: The MPU9250 is an I2C sensor and uses the Arduino Wire library.
Because the sensor is not 5V tolerant, we are using a 3.3 V 8 MHz Pro Mini or a 3.3 V Teensy 3.1.
We have disabled the internal pull-ups used by the Wire library in the Wire.h/twi.c utility file.
We are also using the 400 kHz fast I2C mode by setting the TWI_FREQ to 400000L /twi.h utility file.
*/

include <SPI.h>

include <Wire.h>

// See also MPU-9250 Register Map and Descriptions, Revision 4.0, RM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in
// above document; the MPU9250 and MPU9150 are virtually identical but the latter has a different register map
//
//Magnetometer Registers

define AK8963_ADDRESS 0x0C

define WHO_AM_I_AK8963 0x00 // should return 0x48

define INFO 0x01

define AK8963_ST1 0x02 // data ready status bit 0

define AK8963_XOUT_L 0x03 // data

define AK8963_XOUT_H 0x04

define AK8963_YOUT_L 0x05

define AK8963_YOUT_H 0x06

define AK8963_ZOUT_L 0x07

define AK8963_ZOUT_H 0x08

define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status bit 2

define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0

define AK8963_ASTC 0x0C // Self test control

define AK8963_I2CDIS 0x0F // I2C disable

define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value

define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value

define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value

define SELF_TEST_X_GYRO 0x00

define SELF_TEST_Y_GYRO 0x01

define SELF_TEST_Z_GYRO 0x02

/*#define X_FINE_GAIN 0x03 // [7:0] fine gain

define Y_FINE_GAIN 0x04

define Z_FINE_GAIN 0x05

define XA_OFFSET_H 0x06 // User-defined trim values for accelerometer

define XA_OFFSET_L_TC 0x07

define YA_OFFSET_H 0x08

define YA_OFFSET_L_TC 0x09

define ZA_OFFSET_H 0x0A

define ZA_OFFSET_L_TC 0x0B */

define SELF_TEST_X_ACCEL 0x0D

define SELF_TEST_Y_ACCEL 0x0E

define SELF_TEST_Z_ACCEL 0x0F

define SELF_TEST_A 0x10

define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope

define XG_OFFSET_L 0x14

define YG_OFFSET_H 0x15

define YG_OFFSET_L 0x16

define ZG_OFFSET_H 0x17

define ZG_OFFSET_L 0x18

define SMPLRT_DIV 0x19

define CONFIG 0x1A

define GYRO_CONFIG 0x1B

define ACCEL_CONFIG 0x1C

define ACCEL_CONFIG2 0x1D

define LP_ACCEL_ODR 0x1E

define WOM_THR 0x1F

define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms

define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0]

define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms

define FIFO_EN 0x23

define I2C_MST_CTRL 0x24

define I2C_SLV0_ADDR 0x25

define I2C_SLV0_REG 0x26

define I2C_SLV0_CTRL 0x27

define I2C_SLV1_ADDR 0x28

define I2C_SLV1_REG 0x29

define I2C_SLV1_CTRL 0x2A

define I2C_SLV2_ADDR 0x2B

define I2C_SLV2_REG 0x2C

define I2C_SLV2_CTRL 0x2D

define I2C_SLV3_ADDR 0x2E

define I2C_SLV3_REG 0x2F

define I2C_SLV3_CTRL 0x30

define I2C_SLV4_ADDR 0x31

define I2C_SLV4_REG 0x32

define I2C_SLV4_DO 0x33

define I2C_SLV4_CTRL 0x34

define I2C_SLV4_DI 0x35

define I2C_MST_STATUS 0x36

define INT_PIN_CFG 0x37

define INT_ENABLE 0x38

define DMP_INT_STATUS 0x39 // Check DMP interrupt

define INT_STATUS 0x3A

define ACCEL_XOUT_H 0x3B

define ACCEL_XOUT_L 0x3C

define ACCEL_YOUT_H 0x3D

define ACCEL_YOUT_L 0x3E

define ACCEL_ZOUT_H 0x3F

define ACCEL_ZOUT_L 0x40

define TEMP_OUT_H 0x41

define TEMP_OUT_L 0x42

define GYRO_XOUT_H 0x43

define GYRO_XOUT_L 0x44

define GYRO_YOUT_H 0x45

define GYRO_YOUT_L 0x46

define GYRO_ZOUT_H 0x47

define GYRO_ZOUT_L 0x48

define EXT_SENS_DATA_00 0x49

define EXT_SENS_DATA_01 0x4A

define EXT_SENS_DATA_02 0x4B

define EXT_SENS_DATA_03 0x4C

define EXT_SENS_DATA_04 0x4D

define EXT_SENS_DATA_05 0x4E

define EXT_SENS_DATA_06 0x4F

define EXT_SENS_DATA_07 0x50

define EXT_SENS_DATA_08 0x51

define EXT_SENS_DATA_09 0x52

define EXT_SENS_DATA_10 0x53

define EXT_SENS_DATA_11 0x54

define EXT_SENS_DATA_12 0x55

define EXT_SENS_DATA_13 0x56

define EXT_SENS_DATA_14 0x57

define EXT_SENS_DATA_15 0x58

define EXT_SENS_DATA_16 0x59

define EXT_SENS_DATA_17 0x5A

define EXT_SENS_DATA_18 0x5B

define EXT_SENS_DATA_19 0x5C

define EXT_SENS_DATA_20 0x5D

define EXT_SENS_DATA_21 0x5E

define EXT_SENS_DATA_22 0x5F

define EXT_SENS_DATA_23 0x60

define MOT_DETECT_STATUS 0x61

define I2C_SLV0_DO 0x63

define I2C_SLV1_DO 0x64

define I2C_SLV2_DO 0x65

define I2C_SLV3_DO 0x66

define I2C_MST_DELAY_CTRL 0x67

define SIGNAL_PATH_RESET 0x68

define MOT_DETECT_CTRL 0x69

define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP

define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode

define PWR_MGMT_2 0x6C

define DMP_BANK 0x6D // Activates a specific bank in the DMP

define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start address in specified DMP bank

define DMP_REG 0x6F // Register in DMP from which to read or to which to write

define DMP_REG_1 0x70

define DMP_REG_2 0x71

define FIFO_COUNTH 0x72

define FIFO_COUNTL 0x73

define FIFO_R_W 0x74

define WHO_AM_I_MPU9250 0x75 // Should return 0x71

define XA_OFFSET_H 0x77

define XA_OFFSET_L 0x78

define YA_OFFSET_H 0x7A

define YA_OFFSET_L 0x7B

define ZA_OFFSET_H 0x7D

define ZA_OFFSET_L 0x7E

// Using the MSENSR-9250 breakout board, ADO is set to 0
// Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1

define ADO 1

if ADO

define MPU9250_ADDRESS 0x68 // Device address when ADO = 1

else

define MPU9250_ADDRESS 0x69 // Device address when ADO = 0

define AK8963_ADDRESS 0x0C // Address of magnetometer

endif

define AHRS true // set to false for basic data read

define SerialDebug true // set to true to get Serial output for debugging

// Set initial input parameters
enum Ascale {
AFS_2G = 0,
AFS_4G,
AFS_8G,
AFS_16G
};

enum Gscale {
GFS_250DPS = 0,
GFS_500DPS,
GFS_1000DPS,
GFS_2000DPS
};

enum Mscale {
MFS_14BITS = 0, // 0.6 mG per LSB
MFS_16BITS // 0.15 mG per LSB
};

// Specify sensor full scale
uint8_t Gscale = GFS_250DPS;
uint8_t Ascale = AFS_2G;
uint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer resolution
uint8_t Mmode = 0x02; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read
float aRes, gRes, mRes; // scale resolutions per LSB for the sensors

// Pin definitions
int intPin = 12; // These can be changed, 2 and 3 are the Arduinos ext int pins
int myLed = 13; // Set up pin 13 led for toggling

int16_t accelCount[3]; // Stores the 16-bit signed accelerometer sensor output
int16_t gyroCount[3]; // Stores the 16-bit signed gyro sensor output
int16_t magCount[3]; // Stores the 16-bit signed magnetometer sensor output
float magCalibration[3] = {0, 0, 0}, magbias[3] = {0, 0, 0}; // Factory mag calibration and mag bias
float gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}; // Bias corrections for gyro and accelerometer
int16_t tempCount; // temperature raw count output
float temperature; // Stores the real internal chip temperature in degrees Celsius
float SelfTest[6]; // holds results of gyro and accelerometer self test

// global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
// There is a tradeoff in the beta parameter between accuracy and response speed.
// In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.
// However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.
// Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!
// By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec
// I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense;
// the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy.
// In any case, this is the free parameter in the Madgwick filtering and fusion scheme.
float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta
float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value

define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral

define Ki 0.0f

uint32_t delt_t = 0; // used to control display output rate
uint32_t count = 0, sumCount = 0; // used to control display output rate
float pitch, yaw, roll;
float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t Now = 0; // used to calculate integration interval

float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values
float q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion
float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method

void setup()
{
Wire.begin();
// TWBR = 12; // 400 kbit/sec I2C speed
Serial.begin(115200);

// Set up the interrupt pin, its set as active high, push-pull
pinMode(intPin, INPUT);
digitalWrite(intPin, LOW);
pinMode(myLed, OUTPUT);
digitalWrite(myLed, HIGH);

delay(1000);

// Read the WHO_AM_I register, this is a good test of communication
byte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I register for MPU-9250

delay(1000);

if (c == 0x71) // WHO_AM_I should always be 0x68
{

MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values

calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers


delay(1000); 

initMPU9250(); 

// Serial.println("MPU9250 initialized for active data mode...."); // Initialize device for active mode read of acclerometer, gyroscope, and temperature

// Read the WHO_AM_I register of the magnetometer, this is a good test of communication
byte d = readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);  // Read WHO_AM_I register for AK8963

delay(1000); 

// Get magnetometer calibration from AK8963 ROM
initAK8963(magCalibration); //Serial.println("AK8963 initialized for active data mode...."); // Initialize device for active mode read of magnetometer




delay(1000);  

}
else
{
// Serial.print("Could not connect to MPU9250: 0x");
// Serial.println(c, HEX);
while(1) ; // Loop forever if communication doesn't happen
}
}

void loop()
{
// If intPin goes high, all data registers have new data
if (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) { // On interrupt, check if data ready interrupt
readAccelData(accelCount); // Read the x/y/z adc values
getAres();

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

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

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

readMagData(magCount);  // Read the x/y/z adc values
getMres();
magbias[0] = +281.;  // User environmental x-axis correction in milliGauss, should be automatically calculated
magbias[1] = +231.;  // User environmental x-axis correction in milliGauss
magbias[2] = -406.;  // User environmental x-axis correction in milliGauss

// Calculate the magnetometer values in milliGauss
// Include factory calibration per data sheet and user environmental corrections
mx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0];  // get actual magnetometer value, this depends on scale being set
my = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];  
mz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2]; 


    ax=ax-850/1000;
ay=ay-850/1000;
az=az+500/1000;

}

Now = micros();
deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
lastUpdate = Now;

sum += deltat; // sum for averaging filter update rate
sumCount++;

// Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer;
// the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of accelerometer and gyro!
// We have to make some allowance for this orientationmismatch in feeding the output to the quaternion filter.
// For the MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like
// in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention.
// This is ok by aircraft orientation standards!
// Pass gyro rate as rad/s
MadgwickQuaternionUpdate(ax, ay, az, gx_PI/180.0f, gy_PI/180.0f, gz_PI/180.0f, my, mx, mz);
//MahonyQuaternionUpdate(ax, ay, az, gx_PI/180.0f, gy_PI/180.0f, gz_PI/180.0f, my, mx, mz);

// Serial print and/or display at 0.5 s rate independent of data rates
delt_t = millis() - count;
if (delt_t > 50) { // update LCD once per half-second independent of read rate

if(SerialDebug) {

// Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.
// In this coordinate system, the positive z-axis is down toward Earth.
// Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
// Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
// Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
// These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
// Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
// applied in the correct order which for this configuration is yaw, pitch, and then roll.
// For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
yaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
roll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
pitch *= 180.0f / PI;
yaw *= 180.0f / PI;
//yaw -= 13.8; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
roll *= 180.0f / PI;

if(SerialDebug) {
//Serial.print("Yaw, Pitch, Roll: ");
int sensorvalue = analogRead (A2);

Serial.print(sensorvalue);
Serial.print("\t");
Serial.print(yaw, 2);
Serial.print("\t");
Serial.print(pitch, 2);
Serial.print("\t");
Serial.println(roll, 2);

//Serial.print("rate = "); Serial.print((float)sumCount/sum, 2); Serial.println(" Hz");
}



// With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and 
// >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz.
// The filter update rate is determined mostly by the mathematical steps in the respective algorithms, 
// the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR:
// an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces
// filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively. 
// This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads.
// This filter update rate should be fast enough to maintain accurate platform orientation for 
// stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz
// produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors.
// The 3.3 V 8 MHz Pro Mini is doing pretty well!
//display.setCursor(0, 40); display.print("rt: "); display.print((float) sumCount / sum, 2); display.print(" Hz"); 
//display.display();

count = millis(); 
sumCount = 0;
sum = 0;    
}
}

}

//===================================================================================================================
//====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data
//===================================================================================================================

void getMres() {
switch (Mscale)
{
// Possible magnetometer scales (and their register bit settings) are:
// 14 bit resolution (0) and 16 bit resolution (1)
case MFS_14BITS:
mRes = 10._4912./8190.; // Proper scale to return milliGauss
break;
case MFS_16BITS:
mRes = 10._4912./32760.0; // Proper scale to return milliGauss
break;
}
}

void getGres() {
switch (Gscale)
{
// Possible gyro scales (and their register bit settings) are:
// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case GFS_250DPS:
gRes = 250.0/32768.0;
break;
case GFS_500DPS:
gRes = 500.0/32768.0;
break;
case GFS_1000DPS:
gRes = 1000.0/32768.0;
break;
case GFS_2000DPS:
gRes = 2000.0/32768.0;
break;
}
}

void getAres() {
switch (Ascale)
{
// Possible accelerometer scales (and their register bit settings) are:
// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case AFS_2G:
aRes = 2.0/32768.0;
break;
case AFS_4G:
aRes = 4.0/32768.0;
break;
case AFS_8G:
aRes = 8.0/32768.0;
break;
case AFS_16G:
aRes = 16.0/32768.0;
break;
}
}

void readAccelData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z accel register data stored here
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}

void readGyroData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}

void readMagData(int16_t * destination)
{
uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition
if(readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01) { // wait for magnetometer data ready bit to be set
readBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]); // Read the six raw data and ST2 registers sequentially into data array
uint8_t c = rawData[6]; // End data read by reading ST2 register
if(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then report data
destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as little Endian
destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}
}
}

int16_t readTempData()
{
uint8_t rawData[2]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw data registers sequentially into data array
return ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a 16-bit value
}

void initAK8963(float * destination)
{
// First extract the factory calibration for each magnetometer axis
uint8_t rawData[3]; // x/y/z gyro calibration data stored here
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode
delay(10);
readBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]); // Read the x-, y-, and z-axis calibration values
destination[0] = (float)(rawData[0] - 128)/256. + 1.; // Return x-axis sensitivity adjustment values, etc.
destination[1] = (float)(rawData[1] - 128)/256. + 1.;
destination[2] = (float)(rawData[2] - 128)/256. + 1.;
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
// Configure the magnetometer for continuous read and highest resolution
// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,
// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates
writeByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR
delay(10);
}

void initMPU9250()
{
// wake up device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors
delay(100); // Wait for all registers to reset

// get stable time source
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // Auto select clock source to be PLL gyroscope reference if ready else
delay(200);

// Configure Gyro and Thermometer
// Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
// minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
// be higher than 1 / 0.0059 = 170 Hz
// DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
// With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x03);

// Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; a rate consistent with the filter update rate
// determined inset in CONFIG above

// Set gyroscope full scale range
// Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);
// writeRegister(GYRO_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x02); // Clear Fchoice bits [1:0]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c | Gscale << 3); // Set full scale range for the gyro
// writeRegister(GYRO_CONFIG, c | 0x00); // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG

// Set accelerometer full-scale range configuration
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG);
// writeRegister(ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c | Ascale << 3); // Set full scale range for the accelerometer

// Set accelerometer sample rate configuration
// It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for
// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2);
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c & ~0x0F); // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c | 0x03); // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz

// The accelerometer, gyro, and thermometer are set to 1 kHz sample rates,
// but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting

// Configure Interrupts and Bypass Enable
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips
// can join the I2C bus and all can be controlled by the Arduino as master
writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22);
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt
delay(100);
}

// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
void calibrateMPU9250(float * dest1, float * dest2)
{
uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data
uint16_t ii, packet_count, fifo_count;
int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0};

// reset device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
delay(100);

// get stable time source; Auto select clock source to be PLL gyroscope reference if ready
// else use the internal oscillator, bits 2:0 = 001
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
writeByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);
delay(200);

// Configure device for bias calculation
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source
writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP
delay(15);

// Configure MPU6050 gyro and accelerometer for bias calculation
writeByte(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity

uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec
uint16_t accelsensitivity = 16384; // = 16384 LSB/g

// Configure FIFO to capture accelerometer and gyro data for bias calculation

writeByte(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 512 bytes in MPU-9150)
delay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes

// At end of sample accumulation, turn off FIFO sensor read
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer sensors for FIFO
readBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count
fifo_count = ((uint16_t)data[0] << 8) | data[1];
packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging

for (ii = 0; ii < packet_count; ii++) {
int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};
readBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging
accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form signed 16-bit integer for each sample in FIFO
accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ;
accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ;
gyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ;
gyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ;
gyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;

accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases
accel_bias[1] += (int32_t) accel_temp[1];
accel_bias[2] += (int32_t) accel_temp[2];
gyro_bias[0]  += (int32_t) gyro_temp[0];
gyro_bias[1]  += (int32_t) gyro_temp[1];
gyro_bias[2]  += (int32_t) gyro_temp[2];

}
accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases
accel_bias[1] /= (int32_t) packet_count;
accel_bias[2] /= (int32_t) packet_count;
gyro_bias[0] /= (int32_t) packet_count;
gyro_bias[1] /= (int32_t) packet_count;
gyro_bias[2] /= (int32_t) packet_count;

if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} // Remove gravity from the z-axis accelerometer bias calculation
else {accel_bias[2] += (int32_t) accelsensitivity;}

// Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup
data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format
data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases
data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;
data[3] = (-gyro_bias[1]/4) & 0xFF;
data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;
data[5] = (-gyro_bias[2]/4) & 0xFF;

// Push gyro biases to hardware registers
writeByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);
writeByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);

// Output scaled gyro biases for display in the main program
dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;
dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;
dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;

// Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain
// factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold
// non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature
// compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that
// the accelerometer biases calculated above must be divided by 8.

int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases
readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values
accel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]);
accel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]);
accel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]);

uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers
uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis

for(ii = 0; ii < 3; ii++) {
if((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit
}

// Construct total accelerometer bias, including calculated average accelerometer bias from above
accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg[1] -= (accel_bias[1]/8);
accel_bias_reg[2] -= (accel_bias[2]/8);

data[0] = (accel_bias_reg[0] >> 8) & 0xFF;
data[1] = (accel_bias_reg[0]) & 0xFF;
data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[2] = (accel_bias_reg[1] >> 8) & 0xFF;
data[3] = (accel_bias_reg[1]) & 0xFF;
data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[4] = (accel_bias_reg[2] >> 8) & 0xFF;
data[5] = (accel_bias_reg[2]) & 0xFF;
data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers

// Apparently this is not working for the acceleration biases in the MPU-9250
// Are we handling the temperature correction bit properly?
// Push accelerometer biases to hardware registers
writeByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);
writeByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);
writeByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);
writeByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);
writeByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);
writeByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);

// Output scaled accelerometer biases for display in the main program
dest2[0] = (float)accel_bias[0]/(float)accelsensitivity;
dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;
dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;
}

// Accelerometer and gyroscope self test; check calibration wrt factory settings
void MPU9250SelfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass
{
uint8_t rawData[6] = {0, 0, 0, 0, 0, 0};
uint8_t selfTest[6];
int16_t gAvg[3], aAvg[3], aSTAvg[3], gSTAvg[3];
float factoryTrim[6];
uint8_t FS = 0;

writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz and DLPF to 92 Hz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 1<<FS); // Set full scale range for the gyro to 250 dps
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 1<<FS); // Set full scale range for the accelerometer to 2 g

for( int ii = 0; ii < 200; ii++) { // get average current values of gyro and acclerometer

readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;

readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);       // Read the six raw data registers sequentially into data array

gAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}

for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average current readings
aAvg[ii] /= 200;
gAvg[ii] /= 200;
}

// Configure the accelerometer for self-test
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s
delay(25); // Delay a while to let the device stabilize

for( int ii = 0; ii < 200; ii++) { // get average self-test values of gyro and acclerometer

readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;

readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array

gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}

for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average self-test readings
aSTAvg[ii] /= 200;
gSTAvg[ii] /= 200;
}

// Configure the gyro and accelerometer for normal operation
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);
delay(25); // Delay a while to let the device stabilize

// Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg
selfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel self-test results
selfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel self-test results
selfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel self-test results
selfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO); // X-axis gyro self-test results
selfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO); // Y-axis gyro self-test results
selfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO); // Z-axis gyro self-test results

// Retrieve factory self-test value from self-test code reads
factoryTrim[0] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[0] - 1.0) )); // FT[Xa] factory trim calculation
factoryTrim[1] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[1] - 1.0) )); // FT[Ya] factory trim calculation
factoryTrim[2] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[2] - 1.0) )); // FT[Za] factory trim calculation
factoryTrim[3] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[3] - 1.0) )); // FT[Xg] factory trim calculation
factoryTrim[4] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[4] - 1.0) )); // FT[Yg] factory trim calculation
factoryTrim[5] = (float)(2620/1<<FS)
(pow( 1.01 , ((float)selfTest[5] - 1.0) )); // FT[Zg] factory trim calculation

// Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response
// To get percent, must multiply by 100
for (int i = 0; i < 3; i++) {
destination[i] = 100.0_((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i]; // Report percent differences
destination[i+3] = 100.0_((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3]; // Report percent differences
}

}

    // Wire.h read and write protocols
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)

{
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.write(data); // Put data in Tx buffer
Wire.endTransmission(); // Send the Tx buffer
}

    uint8_t readByte(uint8_t address, uint8_t subAddress)

{
uint8_t data; // data will store the register data
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
Wire.requestFrom(address, (uint8_t) 1); // Read one byte from slave register address
data = Wire.read(); // Fill Rx buffer with result
return data; // Return data read from slave register
}

    void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)

{
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
uint8_t i = 0;
Wire.requestFrom(address, count); // Read bytes from slave register address
while (Wire.available()) {
dest[i++] = Wire.read(); } // Put read results in the Rx buffer
}

void MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;

// Auxiliary variables to avoid repeated arithmetic
float _2q1mx;
float _2q1my;
float _2q1mz;
float _2q2mx;
float _4bx;
float _4bz;
float _2q1 = 2.0f * q1;
float _2q2 = 2.0f * q2;
float _2q3 = 2.0f * q3;
float _2q4 = 2.0f * q4;
float _2q1q3 = 2.0f * q1 * q3;
float _2q3q4 = 2.0f * q3 * q4;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;

// Normalise accelerometer measurement
norm = sqrt(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f/norm;
ax *= norm;
ay *= norm;
az *= norm;

// Normalise magnetometer measurement
norm = sqrt(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f/norm;
mx *= norm;
my *= norm;
mz *= norm;

// Reference direction of Earth's magnetic field
_2q1mx = 2.0f * q1 * mx;
_2q1my = 2.0f * q1 * my;
_2q1mz = 2.0f * q1 * mz;
_2q2mx = 2.0f * q2 * mx;
hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
_2bx = sqrt(hx * hx + hy * hy);
_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
_4bx = 2.0f * _2bx;
_4bz = 2.0f * _2bz;

// Gradient decent algorithm corrective step
s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
norm = sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude
norm = 1.0f/norm;
s1 *= norm;
s2 *= norm;
s3 *= norm;
s4 *= norm;

// Compute rate of change of quaternion
qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;

// Integrate to yield quaternion
q1 += qDot1 * deltat;
q2 += qDot2 * deltat;
q3 += qDot3 * deltat;
q4 += qDot4 * deltat;
norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
norm = 1.0f/norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;

}

// Similar to Madgwick scheme but uses proportional and integral filtering on the error between estimated reference vectors and
// measured ones.
void MahonyQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;

// Auxiliary variables to avoid repeated arithmetic
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;

// Normalise accelerometer measurement
norm = sqrt(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
ax *= norm;
ay *= norm;
az *= norm;

// Normalise magnetometer measurement
norm = sqrt(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
mx *= norm;
my *= norm;
mz *= norm;

// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrt((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);

// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);

// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
if (Ki > 0.0f)
{
eInt[0] += ex; // accumulate integral error
eInt[1] += ey;
eInt[2] += ez;
}
else
{
eInt[0] = 0.0f; // prevent integral wind up
eInt[1] = 0.0f;
eInt[2] = 0.0f;
}

// Apply feedback terms
gx = gx + Kp * ex + Ki * eInt[0];
gy = gy + Kp * ey + Ki * eInt[1];
gz = gz + Kp * ez + Ki * eInt[2];

// Integrate rate of change of quaternion
pa = q2;
pb = q3;
pc = q4;
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);

// Normalise quaternion
norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
norm = 1.0f / norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;

}

When IMU moves in 2-D Plane (YZ), accelerometer measures acceleration in third axis (X axis) too?

I am moving my IMU in YZ plane but it accelerometer is measuring considerable acceleration in X axis as well which very closely follows acceleration curve of Y axis.

I am drawing a semi-circle in YZ plane with y-axis as diameter of semi-circle.

Here is the gravity free acceleration curves of all 3 axes:

accelertions

You can see that acceleration in x-axis is of considerable magnitude, so I can't treat it as a noise.

Please help as I am stuck with this problem since 10 days.

Optimal register settings for Teensy 3.1

Kris,

I've been running the EMSENSR-9250 on a Teensy 3.1 using I2C, 72MHz, and your MPU9250BasicAHRS sketch (THANK YOU BTW!). For some reason, I can only get the Mahony Algorithm to run at 1030Hz, (not 2200 has stated in your description). I was wondering the settings you used for CONFIG, SMPLRT_DIV, GYRO_CONFIG, ACCEL_CONFIG, and other relevant registers to achieve 2200 Hz? Also, for some reason when I overclock to 96MHz, my loop rate in the MPU9250BasicAHRS drops to 880Hz, which seems quite odd.

Thanks for any help!

-Corbin

Doesn't seem to be working

Hello Kris,

I have downloaded the source to the 9250 AHRS, but the system dones't seem to be functioning well at all.

The problems i'm experiencing are that the sensor fusion will settle on a value yaw value and whenever the IMU is rotated on the yaw axis, the yaw ill move slightly, and then return to the settled value it initialized to. The roll and the pitch axis are fine and working.

I'm not sure what I should be doing to help correct the problem.

Thanks

Using MPU9250BasicAHRS with Arduino

Hi there,

In your description you say that this code is an Arduino Sketch. I'm fairly new to coding with Arduino and would love to use your libraries/ code to get fused sensor data coming out of my MPU9250 to be logged onto an SD card.

For the time being, I'm taking one step at a time and just want to see the fused sensor values in my serial monitor without any SD card functionality. I am using just an Arduino Uno R3 and MPU9250 breakout from Drotek, see link below, but no Adafruit display that is described in the "MPU9250BasicAHRS.ino" file description. When I run the "MPU9250BasicAHRS.ino" there are obvious problems associated with the fact that I don't have the display libraries/ LCD attached. It won't compile. The MPU9250 I have is on the default I2C bus address 0x68 and is recognised when running an I2C scanner.

I'd like all the functionality you described in the starting comments: "Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor,
getting properly scaled accelerometer, gyroscope, and magnetometer data out. Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms", just without the LCD display. How do I do this? The DMP values I'm particularly interested in having are world frame acceleration in x,y,z and absolute Euler angles for yaw pitch roll, if this is possible.

Could you give any advice (quick step-by-step perhaps) or adapted code that can get this functionality using what I have? I assume it isn't as simple as commenting/ deleting all the calls to the LCD display/libraries? Hopefully your experience can help me out here!

Secondly, I'd like to sample my accel, gyro and mag at a fairly low 25 Hz. Looking through the code I found a number of comments talking about setting sample rates for each accel, gyro, mag and temp sensors but was confused as to exactly how to do this. There's a lot of code here and I don't want to change something somewhere and have it mess up everything else. How do I do this?

If you also have any comments about the feasibility of saving these values to an SD card at 25Hz then I'd be happy to hear them. I'm using the Adafruit datalogging SD card shield, see link below. I tried a while ago to save from an MPU6050 using DMP to an SD card and the FIFO buffer didn't like it, it kept overflowing and everything was very slow. I resorted then to saving only raw sensor values, which worked very well, but I really want to use the fused values for this latest project.

Any advice welcomed! Thank you in advance, looking forward to hearing your comments.

Best,
Chris

Drotek sensor (assembled for I2C):
http://www.drotek.com/shop/en/home/421-mpu9250-gyro-accelerometer-magnetometer.html?search_query=mpu9250&results=3

Adafruit SD shield:
https://www.adafruit.com/products/1141

One Question

Hello

I am working on a project; using mpu9250 on stm32f4 discovery board. I have two issues with the device and will be pleased if some one helps.
First;
I am trying to configure PWR_1 register and clock source but it does not work.
I do the following :
disabling sleep mode ; writing 0x00 to PWR_1
wait(100 ms)
choosing clock source to one of pll sources ; writing 0x02 ... 0x05 to PWR_1
after such a configuration i have still unstable gyro values and a wrong temperature value.
Second;
When using AK.. magnetometer; I have just enabled the bypass bit and them configured the magnetometer . I think that the outputs are wrong. in 14 bit mode i receive [50 30 45] for example when having 90 degrees drift from north. the outputs do not agree whit environmental facts?
if there is any idea please share with me.
thanks

Problem with magnetometer

Thanks for your sharing.

I use stm32F407 board and its spi interface to get the data.
here is my initialization:

{0x00, MPU6500_PWR_MGMT_1},
{0x01, MPU6500_PWR_MGMT_1}, // Clock Source
{0x00, MPU6500_PWR_MGMT_2}, // Enable Acc & Gyro
{0x07, MPU6500_CONFIG}, //
{0x18, MPU6500_GYRO_CONFIG}, // +-2000dps
{0x08, MPU6500_ACCEL_CONFIG}, // +-4G
{0x00, MPU6500_ACCEL_CONFIG_2}, // Set Acc Data Rates
{0x22, MPU6500_INT_PIN_CFG}, // Configure Interrupts and Bypass Enable
{0x01, MPU6500_INT_ENABLE}, //
{0x40, MPU6500_I2C_MST_CTRL}, // I2C Speed 348 kHz
{0x00, AK8963_CNTL1}, // Power down mag
{0x16, AK8963_CNTL1}, // set sampling rate 100Hz

but when I read the data, it didn't change. like keep showing -25346

is there anything wrong for my initialization?
Thank again.

Accelerometer calibration

Hi,

for calibration of the accelerometer, you divide the bias by 8 :
accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg[1] -= (accel_bias[1]/8);
accel_bias_reg[2] -= (accel_bias[2]/8);

But for accelerometer, offset is for all Full Scale Range with 1024 LSB/g sensitivity, and since measurement are made in 16384 LSB/g, bias has to be divided by 16.

Cannot connect to MPU-9250. It returns 0x73 instead of 0x71

So everytime i try to connect, it prints this message -

MPU9250 I AM 73 I should be 71
Could not connect to MPU9250: 0x73

I have completed i2c scans and received raw data from my sensor before so i'm not sure what i'm doing wrong. Thanks in advance

Yaw Pitch Roll Estimation

Hello Kris,
Hope you are doing good.
I am having some problems while estimating YPR. I am reading data from FIFO at 1kHz with BW 184 Hz and then magneto at 100Hz (i hope 0x12 and 0x16 setting on CNTL does that job). Now I have got the scale and offset separately via offline and is being continuously subtracted and scaled for accelero, gyro and magneto. Now this one time calibrated data is sent to Madgwick filter. I am not sure the order to be sent. Madwick seems to use NED but the code that you shared does not follow that. It is in NWUp for accelro/gyro and NWDown for magneto. I am not sure how this could be done. After this I have the quat -> rotmatrix conversion and then calculation of euler angle using ZXY sequence. The angle that I calculate is not linearly incrementing but at some angle it is stationary and at some small angle change there is a large variation. Can you give me some idea to solve this issue ?
Thanks and Regards,
Akhil

Magnetometer

Hi kriswiner. I have been following your work with imu. a few questions:
have you already tested mpu9250 using spi? The pass-through mode is only for I2C or SPI too?
I'm not using the pass-through mode but my yaw drift alot (a degree per second), i don´t know if the data of magnetometer axis are correct and sometimes stop reading. Can you help me?
thanks alot

Yaw Pitch and Roll Estimation

Hello Kris,

I am back with more questions.

  1. In the MPU9250 algo you have derived the Euler angles from quaternion representing orinatation of sensor wrt NED frame. How did you decided you pick one rotation sequences (Tait Bryan, Euler angle) and what is the basis of selection.Depending on the selection you have different set of Y,P and R values and out of which one is correct for one case. I have read a bit on this and discussed with few of my friends,but did not understood the matter well.
  2. What is sensor to segment calibration and can you give me a simple example to understand this?
  3. The system calculates accelero/gyro biases and magneto hard iron biases. How do I verify whether this is enough ?

I know I have asked too many theoretical questions, but hope at least you would be able to provide some materials or the path through which I have to look .

Thanks and Regards,
Akhil.

Magnetometer shows same data in all the axes.

Hello,

I am trying to read magnetometer data from MPU9250 using dsPIC33F. The code was running well in MPU9150 platform and when I tried porting (with modification on the Bypass Enable bit) to MPU9250 it does not work.
I am able to read device ID and it shows 0x48. Then I did tried to read the calibration data by reading from ASAX,ASAY,ASAZ. This executes but all the data are the same. Then I tried to read the magneto registers by,

setting INT_PIN_CFG = 0x02 (this is as part of the initialisation of IMU)
power down and then setting AK8963_CNTL = 0x02 and tried 0x01 too (delay of 10ms)
read magneto registers and ST2 (as in datasheet they say in continuous mode we have to read ST2)
I am able to read accelerometer and gyroscope by populating it to FIFO and this part works well.At this stage am able to read data and which is sensitive to external mag field too but the mx,my, and mz values are the same.

Could you help me to sort out this issue ? (Think timing delay is the culprit, and I am not using Interrupt lines)

Thanks :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.