{"action":"created","issue":{"url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/22","labels_url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/22/labels{/name}","comments_url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/22/comments","events_url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/22/events","html_url":"https://github.com/kriswiner/MPU-9250/issues/22","id":108383683,"number":22,"title":"pitch, yaw, roll Interrupting each other!","user":{"login":"Navid360","id":14235894,"avatar_url":"https://avatars.githubusercontent.com/u/14235894?v=3","gravatar_id":"","url":"https://api.github.com/users/Navid360","html_url":"https://github.com/Navid360","followers_url":"https://api.github.com/users/Navid360/followers","following_url":"https://api.github.com/users/Navid360/following{/other_user}","gists_url":"https://api.github.com/users/Navid360/gists{/gist_id}","starred_url":"https://api.github.com/users/Navid360/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/Navid360/subscriptions","organizations_url":"https://api.github.com/users/Navid360/orgs","repos_url":"https://api.github.com/users/Navid360/repos","events_url":"https://api.github.com/users/Navid360/events{/privacy}","received_events_url":"https://api.github.com/users/Navid360/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":0,"created_at":"2015-09-25T18:31:33Z","updated_at":"2015-09-25T18:40:41Z","closed_at":null,"body":"Hi Kris\r\nI am running the attached code on a Teensy3.1 and a cheap MPU9250 \r\n(http://www.ebay.com/itm/SPI-IIC-MPU-9250-9-Axis-Attitude-Gyro-Accelerator-Magnetometer-Sensor-Module-/131185485892)\r\n\r\nI 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.\r\n\r\nWould you please let me know what is wrong with it?\r\n\r\nThanks\r\nNavid\r\n\r\n\r\nHere is my Code:   \r\n\r\n/* MPU9250 Basic Example Code\r\n by: Kris Winer\r\n date: April 1, 2014\r\n license: Beerware - Use this code however you'd like. If you \r\n find it useful you can buy me a beer some time.\r\n \r\n Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor, \r\n getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to \r\n allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and \r\n Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1.\r\n \r\n SDA and SCL should have external pull-up resistors (to 3.3V).\r\n 10k resistors are on the EMSENSR-9250 breakout board.\r\n \r\n Hardware setup:\r\n MPU9250 Breakout --------- Arduino\r\n VDD ---------------------- 3.3V\r\n VDDI --------------------- 3.3V\r\n SDA ----------------------- A4\r\n SCL ----------------------- A5\r\n GND ---------------------- GND\r\n \r\n Note: The MPU9250 is an I2C sensor and uses the Arduino Wire library. \r\n 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.\r\n We have disabled the internal pull-ups used by the Wire library in the Wire.h/twi.c utility file.\r\n We are also using the 400 kHz fast I2C mode by setting the TWI_FREQ  to 400000L /twi.h utility file.\r\n */\r\n#include <SPI.h>\r\n#include <Wire.h>   \r\n\r\n\r\n\r\n\r\n// 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 \r\n// above document; the MPU9250 and MPU9150 are virtually identical but the latter has a different register map\r\n//\r\n//Magnetometer Registers\r\n#define AK8963_ADDRESS   0x0C\r\n#define WHO_AM_I_AK8963  0x00 // should return 0x48\r\n#define INFO             0x01\r\n#define AK8963_ST1       0x02  // data ready status bit 0\r\n#define AK8963_XOUT_L   0x03  // data\r\n#define AK8963_XOUT_H  0x04\r\n#define AK8963_YOUT_L  0x05\r\n#define AK8963_YOUT_H  0x06\r\n#define AK8963_ZOUT_L  0x07\r\n#define AK8963_ZOUT_H  0x08\r\n#define AK8963_ST2       0x09  // Data overflow bit 3 and data read error status bit 2\r\n#define AK8963_CNTL      0x0A  // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0\r\n#define AK8963_ASTC      0x0C  // Self test control\r\n#define AK8963_I2CDIS    0x0F  // I2C disable\r\n#define AK8963_ASAX      0x10  // Fuse ROM x-axis sensitivity adjustment value\r\n#define AK8963_ASAY      0x11  // Fuse ROM y-axis sensitivity adjustment value\r\n#define AK8963_ASAZ      0x12  // Fuse ROM z-axis sensitivity adjustment value\r\n\r\n#define SELF_TEST_X_GYRO 0x00                  \r\n#define SELF_TEST_Y_GYRO 0x01                                                                          \r\n#define SELF_TEST_Z_GYRO 0x02\r\n\r\n/*#define X_FINE_GAIN      0x03 // [7:0] fine gain\r\n#define Y_FINE_GAIN      0x04\r\n#define Z_FINE_GAIN      0x05\r\n#define XA_OFFSET_H      0x06 // User-defined trim values for accelerometer\r\n#define XA_OFFSET_L_TC   0x07\r\n#define YA_OFFSET_H      0x08\r\n#define YA_OFFSET_L_TC   0x09\r\n#define ZA_OFFSET_H      0x0A\r\n#define ZA_OFFSET_L_TC   0x0B */\r\n\r\n#define SELF_TEST_X_ACCEL 0x0D\r\n#define SELF_TEST_Y_ACCEL 0x0E    \r\n#define SELF_TEST_Z_ACCEL 0x0F\r\n\r\n#define SELF_TEST_A      0x10\r\n\r\n#define XG_OFFSET_H      0x13  // User-defined trim values for gyroscope\r\n#define XG_OFFSET_L      0x14\r\n#define YG_OFFSET_H      0x15\r\n#define YG_OFFSET_L      0x16\r\n#define ZG_OFFSET_H      0x17\r\n#define ZG_OFFSET_L      0x18\r\n#define SMPLRT_DIV       0x19\r\n#define CONFIG           0x1A\r\n#define GYRO_CONFIG      0x1B\r\n#define ACCEL_CONFIG     0x1C\r\n#define ACCEL_CONFIG2    0x1D\r\n#define LP_ACCEL_ODR     0x1E   \r\n#define WOM_THR          0x1F   \r\n\r\n#define MOT_DUR          0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms\r\n#define ZMOT_THR         0x21  // Zero-motion detection threshold bits [7:0]\r\n#define ZRMOT_DUR        0x22  // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms\r\n\r\n#define FIFO_EN          0x23\r\n#define I2C_MST_CTRL     0x24   \r\n#define I2C_SLV0_ADDR    0x25\r\n#define I2C_SLV0_REG     0x26\r\n#define I2C_SLV0_CTRL    0x27\r\n#define I2C_SLV1_ADDR    0x28\r\n#define I2C_SLV1_REG     0x29\r\n#define I2C_SLV1_CTRL    0x2A\r\n#define I2C_SLV2_ADDR    0x2B\r\n#define I2C_SLV2_REG     0x2C\r\n#define I2C_SLV2_CTRL    0x2D\r\n#define I2C_SLV3_ADDR    0x2E\r\n#define I2C_SLV3_REG     0x2F\r\n#define I2C_SLV3_CTRL    0x30\r\n#define I2C_SLV4_ADDR    0x31\r\n#define I2C_SLV4_REG     0x32\r\n#define I2C_SLV4_DO      0x33\r\n#define I2C_SLV4_CTRL    0x34\r\n#define I2C_SLV4_DI      0x35\r\n#define I2C_MST_STATUS   0x36\r\n#define INT_PIN_CFG      0x37\r\n#define INT_ENABLE       0x38\r\n#define DMP_INT_STATUS   0x39  // Check DMP interrupt\r\n#define INT_STATUS       0x3A\r\n#define ACCEL_XOUT_H     0x3B\r\n#define ACCEL_XOUT_L     0x3C\r\n#define ACCEL_YOUT_H     0x3D\r\n#define ACCEL_YOUT_L     0x3E\r\n#define ACCEL_ZOUT_H     0x3F\r\n#define ACCEL_ZOUT_L     0x40\r\n#define TEMP_OUT_H       0x41\r\n#define TEMP_OUT_L       0x42\r\n#define GYRO_XOUT_H      0x43\r\n#define GYRO_XOUT_L      0x44\r\n#define GYRO_YOUT_H      0x45\r\n#define GYRO_YOUT_L      0x46\r\n#define GYRO_ZOUT_H      0x47\r\n#define GYRO_ZOUT_L      0x48\r\n#define EXT_SENS_DATA_00 0x49\r\n#define EXT_SENS_DATA_01 0x4A\r\n#define EXT_SENS_DATA_02 0x4B\r\n#define EXT_SENS_DATA_03 0x4C\r\n#define EXT_SENS_DATA_04 0x4D\r\n#define EXT_SENS_DATA_05 0x4E\r\n#define EXT_SENS_DATA_06 0x4F\r\n#define EXT_SENS_DATA_07 0x50\r\n#define EXT_SENS_DATA_08 0x51\r\n#define EXT_SENS_DATA_09 0x52\r\n#define EXT_SENS_DATA_10 0x53\r\n#define EXT_SENS_DATA_11 0x54\r\n#define EXT_SENS_DATA_12 0x55\r\n#define EXT_SENS_DATA_13 0x56\r\n#define EXT_SENS_DATA_14 0x57\r\n#define EXT_SENS_DATA_15 0x58\r\n#define EXT_SENS_DATA_16 0x59\r\n#define EXT_SENS_DATA_17 0x5A\r\n#define EXT_SENS_DATA_18 0x5B\r\n#define EXT_SENS_DATA_19 0x5C\r\n#define EXT_SENS_DATA_20 0x5D\r\n#define EXT_SENS_DATA_21 0x5E\r\n#define EXT_SENS_DATA_22 0x5F\r\n#define EXT_SENS_DATA_23 0x60\r\n#define MOT_DETECT_STATUS 0x61\r\n#define I2C_SLV0_DO      0x63\r\n#define I2C_SLV1_DO      0x64\r\n#define I2C_SLV2_DO      0x65\r\n#define I2C_SLV3_DO      0x66\r\n#define I2C_MST_DELAY_CTRL 0x67\r\n#define SIGNAL_PATH_RESET  0x68\r\n#define MOT_DETECT_CTRL  0x69\r\n#define USER_CTRL        0x6A  // Bit 7 enable DMP, bit 3 reset DMP\r\n#define PWR_MGMT_1       0x6B // Device defaults to the SLEEP mode\r\n#define PWR_MGMT_2       0x6C\r\n#define DMP_BANK         0x6D  // Activates a specific bank in the DMP\r\n#define DMP_RW_PNT       0x6E  // Set read/write pointer to a specific start address in specified DMP bank\r\n#define DMP_REG          0x6F  // Register in DMP from which to read or to which to write\r\n#define DMP_REG_1        0x70\r\n#define DMP_REG_2        0x71 \r\n#define FIFO_COUNTH      0x72\r\n#define FIFO_COUNTL      0x73\r\n#define FIFO_R_W         0x74\r\n#define WHO_AM_I_MPU9250 0x75 // Should return 0x71\r\n#define XA_OFFSET_H      0x77\r\n#define XA_OFFSET_L      0x78\r\n#define YA_OFFSET_H      0x7A\r\n#define YA_OFFSET_L      0x7B\r\n#define ZA_OFFSET_H      0x7D\r\n#define ZA_OFFSET_L      0x7E\r\n\r\n// Using the MSENSR-9250 breakout board, ADO is set to 0 \r\n// Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1\r\n#define ADO 1\r\n#if ADO\r\n#define MPU9250_ADDRESS 0x68  // Device address when ADO = 1\r\n#else\r\n#define MPU9250_ADDRESS 0x69  // Device address when ADO = 0\r\n#define AK8963_ADDRESS 0x0C   //  Address of magnetometer\r\n#endif  \r\n\r\n#define AHRS true         // set to false for basic data read\r\n#define SerialDebug true   // set to true to get Serial output for debugging\r\n\r\n// Set initial input parameters\r\nenum Ascale {\r\n  AFS_2G = 0,\r\n  AFS_4G,\r\n  AFS_8G,\r\n  AFS_16G\r\n};\r\n\r\nenum Gscale {\r\n  GFS_250DPS = 0,\r\n  GFS_500DPS,\r\n  GFS_1000DPS,\r\n  GFS_2000DPS\r\n};\r\n\r\nenum Mscale {\r\n  MFS_14BITS = 0, // 0.6 mG per LSB\r\n  MFS_16BITS      // 0.15 mG per LSB\r\n};\r\n\r\n// Specify sensor full scale\r\nuint8_t Gscale = GFS_250DPS;\r\nuint8_t Ascale = AFS_2G;\r\nuint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer resolution\r\nuint8_t Mmode = 0x02;        // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read\r\nfloat aRes, gRes, mRes;      // scale resolutions per LSB for the sensors\r\n  \r\n// Pin definitions\r\nint intPin = 12;  // These can be changed, 2 and 3 are the Arduinos ext int pins\r\nint myLed = 13; // Set up pin 13 led for toggling\r\n\r\nint16_t accelCount[3];  // Stores the 16-bit signed accelerometer sensor output\r\nint16_t gyroCount[3];   // Stores the 16-bit signed gyro sensor output\r\nint16_t magCount[3];    // Stores the 16-bit signed magnetometer sensor output\r\nfloat magCalibration[3] = {0, 0, 0}, magbias[3] = {0, 0, 0};  // Factory mag calibration and mag bias\r\nfloat gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0};      // Bias corrections for gyro and accelerometer\r\nint16_t tempCount;      // temperature raw count output\r\nfloat   temperature;    // Stores the real internal chip temperature in degrees Celsius\r\nfloat   SelfTest[6];    // holds results of gyro and accelerometer self test\r\n\r\n// global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)\r\nfloat GyroMeasError = PI * (40.0f / 180.0f);   // gyroscope measurement error in rads/s (start at 40 deg/s)\r\nfloat GyroMeasDrift = PI * (0.0f  / 180.0f);   // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)\r\n// There is a tradeoff in the beta parameter between accuracy and response speed.\r\n// In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.\r\n// However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.\r\n// Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!\r\n// By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec\r\n// I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense; \r\n// the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy. \r\n// In any case, this is the free parameter in the Madgwick filtering and fusion scheme.\r\nfloat beta = sqrt(3.0f / 4.0f) * GyroMeasError;   // compute beta\r\nfloat 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\r\n#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\r\n#define Ki 0.0f\r\n\r\nuint32_t delt_t = 0; // used to control display output rate\r\nuint32_t count = 0, sumCount = 0; // used to control display output rate\r\nfloat pitch, yaw, roll;\r\nfloat deltat = 0.0f, sum = 0.0f;        // integration interval for both filter schemes\r\nuint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval\r\nuint32_t Now = 0;        // used to calculate integration interval\r\n\r\nfloat ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values \r\nfloat q[4] = {1.0f, 0.0f, 0.0f, 0.0f};    // vector to hold quaternion\r\nfloat eInt[3] = {0.0f, 0.0f, 0.0f};       // vector to hold integral error for Mahony method\r\n\r\n\r\nvoid setup()\r\n{\r\n  Wire.begin();\r\n//  TWBR = 12;  // 400 kbit/sec I2C speed\r\n  Serial.begin(115200);\r\n  \r\n  // Set up the interrupt pin, its set as active high, push-pull\r\n  pinMode(intPin, INPUT);\r\n  digitalWrite(intPin, LOW);\r\n  pinMode(myLed, OUTPUT);\r\n  digitalWrite(myLed, HIGH);\r\n  \r\n\r\n  delay(1000);\r\n\r\n\r\n  // Read the WHO_AM_I register, this is a good test of communication\r\n  byte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250);  // Read WHO_AM_I register for MPU-9250\r\n  \r\n  delay(1000); \r\n\r\n  if (c == 0x71) // WHO_AM_I should always be 0x68\r\n  {  \r\n   \r\n    \r\n    MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values\r\n   \r\n    calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers\r\n\r\n\r\n    delay(1000); \r\n  \r\n    initMPU9250(); \r\n   // Serial.println(\"MPU9250 initialized for active data mode....\"); // Initialize device for active mode read of acclerometer, gyroscope, and temperature\r\n  \r\n    // Read the WHO_AM_I register of the magnetometer, this is a good test of communication\r\n    byte d = readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);  // Read WHO_AM_I register for AK8963\r\n   \r\n    delay(1000); \r\n  \r\n    // Get magnetometer calibration from AK8963 ROM\r\n    initAK8963(magCalibration); //Serial.println(\"AK8963 initialized for active data mode....\"); // Initialize device for active mode read of magnetometer\r\n  \r\n\r\n  \r\n\r\n    delay(1000);  \r\n  }\r\n  else\r\n  {\r\n //   Serial.print(\"Could not connect to MPU9250: 0x\");\r\n   // Serial.println(c, HEX);\r\n    while(1) ; // Loop forever if communication doesn't happen\r\n  }\r\n}\r\n\r\nvoid loop()\r\n{  \r\n  // If intPin goes high, all data registers have new data\r\n  if (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) {  // On interrupt, check if data ready interrupt\r\n    readAccelData(accelCount);  // Read the x/y/z adc values\r\n    getAres();\r\n    \r\n    // Now we'll calculate the accleration value into actual g's\r\n    ax = (float)accelCount[0]*aRes; // - accelBias[0];  // get actual g value, this depends on scale being set\r\n    ay = (float)accelCount[1]*aRes; // - accelBias[1];   \r\n    az = (float)accelCount[2]*aRes; // - accelBias[2];  \r\n   \r\n    readGyroData(gyroCount);  // Read the x/y/z adc values\r\n    getGres();\r\n \r\n    // Calculate the gyro value into actual degrees per second\r\n    gx = (float)gyroCount[0]*gRes;  // get actual gyro value, this depends on scale being set\r\n    gy = (float)gyroCount[1]*gRes;  \r\n    gz = (float)gyroCount[2]*gRes;   \r\n  \r\n    readMagData(magCount);  // Read the x/y/z adc values\r\n    getMres();\r\n    magbias[0] = +281.;  // User environmental x-axis correction in milliGauss, should be automatically calculated\r\n    magbias[1] = +231.;  // User environmental x-axis correction in milliGauss\r\n    magbias[2] = -406.;  // User environmental x-axis correction in milliGauss\r\n    \r\n    // Calculate the magnetometer values in milliGauss\r\n    // Include factory calibration per data sheet and user environmental corrections\r\n    mx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0];  // get actual magnetometer value, this depends on scale being set\r\n    my = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];  \r\n    mz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2]; \r\n\r\n\r\n        ax=ax-850/1000;\r\n    ay=ay-850/1000;\r\n    az=az+500/1000;\r\n  }\r\n  \r\n  Now = micros();\r\n  deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update\r\n  lastUpdate = Now;\r\n\r\n  sum += deltat; // sum for averaging filter update rate\r\n  sumCount++;\r\n  \r\n  // Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer;\r\n  // the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of accelerometer and gyro!\r\n  // We have to make some allowance for this orientationmismatch in feeding the output to the quaternion filter.\r\n  // For the MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like\r\n  // in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention.\r\n  // This is ok by aircraft orientation standards!  \r\n  // Pass gyro rate as rad/s\r\nMadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f,  my,  mx, mz);\r\n //MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz);\r\n\r\n\r\n   \r\n \r\n      \r\n    // Serial print and/or display at 0.5 s rate independent of data rates\r\n    delt_t = millis() - count;\r\n    if (delt_t > 50) { // update LCD once per half-second independent of read rate\r\n\r\n    if(SerialDebug) {\r\n  \r\n            \r\n    \r\n  // Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.\r\n  // In this coordinate system, the positive z-axis is down toward Earth. \r\n  // 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.\r\n  // Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.\r\n  // Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.\r\n  // These arise from the definition of the homogeneous rotation matrix constructed from quaternions.\r\n  // Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be\r\n  // applied in the correct order which for this configuration is yaw, pitch, and then roll.\r\n  // For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.\r\n    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]);   \r\n    pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));\r\n    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]);\r\n    pitch *= 180.0f / PI;\r\n    yaw   *= 180.0f / PI; \r\n    //yaw   -= 13.8; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04\r\n    roll  *= 180.0f / PI;\r\n     \r\n    if(SerialDebug) {\r\n    //Serial.print(\"Yaw, Pitch, Roll: \");\r\n    int sensorvalue = analogRead (A2);\r\nSerial.print(sensorvalue);\r\nSerial.print(\"\\t\");\r\n    Serial.print(yaw, 2);\r\nSerial.print(\"\\t\");\r\n    Serial.print(pitch, 2);\r\n    Serial.print(\"\\t\");\r\n    Serial.println(roll, 2);\r\n    \r\n    //Serial.print(\"rate = \"); Serial.print((float)sumCount/sum, 2); Serial.println(\" Hz\");\r\n    }\r\n   \r\n\r\n  \r\n    // With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and \r\n    // >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz.\r\n    // The filter update rate is determined mostly by the mathematical steps in the respective algorithms, \r\n    // the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR:\r\n    // an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces\r\n    // filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively. \r\n    // This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads.\r\n    // This filter update rate should be fast enough to maintain accurate platform orientation for \r\n    // stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz\r\n    // produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors.\r\n    // The 3.3 V 8 MHz Pro Mini is doing pretty well!\r\n    //display.setCursor(0, 40); display.print(\"rt: \"); display.print((float) sumCount / sum, 2); display.print(\" Hz\"); \r\n    //display.display();\r\n\r\n    count = millis(); \r\n    sumCount = 0;\r\n    sum = 0;    \r\n    }\r\n    }\r\n\r\n}\r\n\r\n//===================================================================================================================\r\n//====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data\r\n//===================================================================================================================\r\n\r\nvoid getMres() {\r\n  switch (Mscale)\r\n  {\r\n  // Possible magnetometer scales (and their register bit settings) are:\r\n  // 14 bit resolution (0) and 16 bit resolution (1)\r\n    case MFS_14BITS:\r\n          mRes = 10.*4912./8190.; // Proper scale to return milliGauss\r\n          break;\r\n    case MFS_16BITS:\r\n          mRes = 10.*4912./32760.0; // Proper scale to return milliGauss\r\n          break;\r\n  }\r\n}\r\n\r\nvoid getGres() {\r\n  switch (Gscale)\r\n  {\r\n  // Possible gyro scales (and their register bit settings) are:\r\n  // 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS  (11). \r\n        // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:\r\n    case GFS_250DPS:\r\n          gRes = 250.0/32768.0;\r\n          break;\r\n    case GFS_500DPS:\r\n          gRes = 500.0/32768.0;\r\n          break;\r\n    case GFS_1000DPS:\r\n          gRes = 1000.0/32768.0;\r\n          break;\r\n    case GFS_2000DPS:\r\n          gRes = 2000.0/32768.0;\r\n          break;\r\n  }\r\n}\r\n\r\nvoid getAres() {\r\n  switch (Ascale)\r\n  {\r\n  // Possible accelerometer scales (and their register bit settings) are:\r\n  // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs  (11). \r\n        // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:\r\n    case AFS_2G:\r\n          aRes = 2.0/32768.0;\r\n          break;\r\n    case AFS_4G:\r\n          aRes = 4.0/32768.0;\r\n          break;\r\n    case AFS_8G:\r\n          aRes = 8.0/32768.0;\r\n          break;\r\n    case AFS_16G:\r\n          aRes = 16.0/32768.0;\r\n          break;\r\n  }\r\n}\r\n\r\n\r\nvoid readAccelData(int16_t * destination)\r\n{\r\n  uint8_t rawData[6];  // x/y/z accel register data stored here\r\n  readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers into data array\r\n  destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;  \r\n  destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; \r\n}\r\n\r\n\r\nvoid readGyroData(int16_t * destination)\r\n{\r\n  uint8_t rawData[6];  // x/y/z gyro register data stored here\r\n  readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array\r\n  destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;  \r\n  destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; \r\n}\r\n\r\nvoid readMagData(int16_t * destination)\r\n{\r\n  uint8_t rawData[7];  // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition\r\n  if(readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01) { // wait for magnetometer data ready bit to be set\r\n  readBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]);  // Read the six raw data and ST2 registers sequentially into data array\r\n  uint8_t c = rawData[6]; // End data read by reading ST2 register\r\n    if(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then report data\r\n    destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ;  // Turn the MSB and LSB into a signed 16-bit value\r\n    destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ;  // Data stored as little Endian\r\n    destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; \r\n   }\r\n  }\r\n}\r\n\r\nint16_t readTempData()\r\n{\r\n  uint8_t rawData[2];  // x/y/z gyro register data stored here\r\n  readBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]);  // Read the two raw data registers sequentially into data array \r\n  return ((int16_t)rawData[0] << 8) | rawData[1] ;  // Turn the MSB and LSB into a 16-bit value\r\n}\r\n       \r\nvoid initAK8963(float * destination)\r\n{\r\n  // First extract the factory calibration for each magnetometer axis\r\n  uint8_t rawData[3];  // x/y/z gyro calibration data stored here\r\n  writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer  \r\n  delay(10);\r\n  writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode\r\n  delay(10);\r\n  readBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]);  // Read the x-, y-, and z-axis calibration values\r\n  destination[0] =  (float)(rawData[0] - 128)/256. + 1.;   // Return x-axis sensitivity adjustment values, etc.\r\n  destination[1] =  (float)(rawData[1] - 128)/256. + 1.;  \r\n  destination[2] =  (float)(rawData[2] - 128)/256. + 1.; \r\n  writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer  \r\n  delay(10);\r\n  // Configure the magnetometer for continuous read and highest resolution\r\n  // set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,\r\n  // and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates\r\n  writeByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR\r\n  delay(10);\r\n}\r\n\r\n\r\nvoid initMPU9250()\r\n{  \r\n // wake up device\r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors \r\n  delay(100); // Wait for all registers to reset \r\n\r\n // get stable time source\r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);  // Auto select clock source to be PLL gyroscope reference if ready else\r\n  delay(200); \r\n  \r\n // Configure Gyro and Thermometer\r\n // Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively; \r\n // minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot\r\n // be higher than 1 / 0.0059 = 170 Hz\r\n // DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both\r\n // With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz\r\n  writeByte(MPU9250_ADDRESS, CONFIG, 0x03);  \r\n\r\n // Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)\r\n  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);  // Use a 200 Hz rate; a rate consistent with the filter update rate \r\n                                    // determined inset in CONFIG above\r\n \r\n // Set gyroscope full scale range\r\n // Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3\r\n  uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);\r\n//  writeRegister(GYRO_CONFIG, c & ~0xE0); // Clear self-test bits [7:5] \r\n  writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x02); // Clear Fchoice bits [1:0] \r\n  writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]\r\n  writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c | Gscale << 3); // Set full scale range for the gyro\r\n // writeRegister(GYRO_CONFIG, c | 0x00); // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG\r\n  \r\n // Set accelerometer full-scale range configuration\r\n  c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG);\r\n//  writeRegister(ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5] \r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]\r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c | Ascale << 3); // Set full scale range for the accelerometer \r\n\r\n // Set accelerometer sample rate configuration\r\n // It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for\r\n // accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz\r\n  c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2);\r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c & ~0x0F); // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])  \r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c | 0x03); // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz\r\n\r\n // The accelerometer, gyro, and thermometer are set to 1 kHz sample rates, \r\n // but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting\r\n\r\n  // Configure Interrupts and Bypass Enable\r\n  // Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,\r\n  // clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips \r\n  // can join the I2C bus and all can be controlled by the Arduino as master\r\n   writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22);    \r\n   writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01);  // Enable data ready (bit 0) interrupt\r\n   delay(100);\r\n}\r\n\r\n\r\n// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average\r\n// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.\r\nvoid calibrateMPU9250(float * dest1, float * dest2)\r\n{  \r\n  uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data\r\n  uint16_t ii, packet_count, fifo_count;\r\n  int32_t gyro_bias[3]  = {0, 0, 0}, accel_bias[3] = {0, 0, 0};\r\n  \r\n // reset device\r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device\r\n  delay(100);\r\n   \r\n // get stable time source; Auto select clock source to be PLL gyroscope reference if ready \r\n // else use the internal oscillator, bits 2:0 = 001\r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);  \r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);\r\n  delay(200);                                    \r\n\r\n// Configure device for bias calculation\r\n  writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x00);   // Disable all interrupts\r\n  writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00);      // Disable FIFO\r\n  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);   // Turn on internal clock source\r\n  writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master\r\n  writeByte(MPU9250_ADDRESS, USER_CTRL, 0x00);    // Disable FIFO and I2C master modes\r\n  writeByte(MPU9250_ADDRESS, USER_CTRL, 0x0C);    // Reset FIFO and DMP\r\n  delay(15);\r\n  \r\n// Configure MPU6050 gyro and accelerometer for bias calculation\r\n  writeByte(MPU9250_ADDRESS, CONFIG, 0x01);      // Set low-pass filter to 188 Hz\r\n  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00);  // Set sample rate to 1 kHz\r\n  writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);  // Set gyro full-scale to 250 degrees per second, maximum sensitivity\r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity\r\n \r\n  uint16_t  gyrosensitivity  = 131;   // = 131 LSB/degrees/sec\r\n  uint16_t  accelsensitivity = 16384;  // = 16384 LSB/g\r\n\r\n    // Configure FIFO to capture accelerometer and gyro data for bias calculation\r\n  writeByte(MPU9250_ADDRESS, USER_CTRL, 0x40);   // Enable FIFO  \r\n  writeByte(MPU9250_ADDRESS, FIFO_EN, 0x78);     // Enable gyro and accelerometer sensors for FIFO  (max size 512 bytes in MPU-9150)\r\n  delay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes\r\n\r\n// At end of sample accumulation, turn off FIFO sensor read\r\n  writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00);        // Disable gyro and accelerometer sensors for FIFO\r\n  readBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count\r\n  fifo_count = ((uint16_t)data[0] << 8) | data[1];\r\n  packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging\r\n  \r\n  for (ii = 0; ii < packet_count; ii++) {\r\n    int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};\r\n    readBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging\r\n    accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1]  ) ;  // Form signed 16-bit integer for each sample in FIFO\r\n    accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3]  ) ;\r\n    accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5]  ) ;    \r\n    gyro_temp[0]  = (int16_t) (((int16_t)data[6] << 8) | data[7]  ) ;\r\n    gyro_temp[1]  = (int16_t) (((int16_t)data[8] << 8) | data[9]  ) ;\r\n    gyro_temp[2]  = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;\r\n    \r\n    accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases\r\n    accel_bias[1] += (int32_t) accel_temp[1];\r\n    accel_bias[2] += (int32_t) accel_temp[2];\r\n    gyro_bias[0]  += (int32_t) gyro_temp[0];\r\n    gyro_bias[1]  += (int32_t) gyro_temp[1];\r\n    gyro_bias[2]  += (int32_t) gyro_temp[2];\r\n            \r\n}\r\n    accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases\r\n    accel_bias[1] /= (int32_t) packet_count;\r\n    accel_bias[2] /= (int32_t) packet_count;\r\n    gyro_bias[0]  /= (int32_t) packet_count;\r\n    gyro_bias[1]  /= (int32_t) packet_count;\r\n    gyro_bias[2]  /= (int32_t) packet_count;\r\n    \r\n  if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;}  // Remove gravity from the z-axis accelerometer bias calculation\r\n  else {accel_bias[2] += (int32_t) accelsensitivity;}\r\n   \r\n// Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup\r\n  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\r\n  data[1] = (-gyro_bias[0]/4)       & 0xFF; // Biases are additive, so change sign on calculated average gyro biases\r\n  data[2] = (-gyro_bias[1]/4  >> 8) & 0xFF;\r\n  data[3] = (-gyro_bias[1]/4)       & 0xFF;\r\n  data[4] = (-gyro_bias[2]/4  >> 8) & 0xFF;\r\n  data[5] = (-gyro_bias[2]/4)       & 0xFF;\r\n  \r\n// Push gyro biases to hardware registers\r\n  writeByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);\r\n  writeByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);\r\n  writeByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);\r\n  writeByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);\r\n  writeByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);\r\n  writeByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);\r\n  \r\n// Output scaled gyro biases for display in the main program\r\n  dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;  \r\n  dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;\r\n  dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;\r\n\r\n// Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain\r\n// factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold\r\n// non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature\r\n// compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that\r\n// the accelerometer biases calculated above must be divided by 8.\r\n\r\n  int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases\r\n  readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values\r\n  accel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\r\n  readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]);\r\n  accel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\r\n  readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]);\r\n  accel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\r\n  \r\n  uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers\r\n  uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis\r\n  \r\n  for(ii = 0; ii < 3; ii++) {\r\n    if((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit\r\n  }\r\n  \r\n  // Construct total accelerometer bias, including calculated average accelerometer bias from above\r\n  accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)\r\n  accel_bias_reg[1] -= (accel_bias[1]/8);\r\n  accel_bias_reg[2] -= (accel_bias[2]/8);\r\n  \r\n  data[0] = (accel_bias_reg[0] >> 8) & 0xFF;\r\n  data[1] = (accel_bias_reg[0])      & 0xFF;\r\n  data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers\r\n  data[2] = (accel_bias_reg[1] >> 8) & 0xFF;\r\n  data[3] = (accel_bias_reg[1])      & 0xFF;\r\n  data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers\r\n  data[4] = (accel_bias_reg[2] >> 8) & 0xFF;\r\n  data[5] = (accel_bias_reg[2])      & 0xFF;\r\n  data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers\r\n \r\n// Apparently this is not working for the acceleration biases in the MPU-9250\r\n// Are we handling the temperature correction bit properly?\r\n// Push accelerometer biases to hardware registers\r\n  writeByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);\r\n  writeByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);\r\n  writeByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);\r\n  writeByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);\r\n  writeByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);\r\n  writeByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);\r\n\r\n// Output scaled accelerometer biases for display in the main program\r\n   dest2[0] = (float)accel_bias[0]/(float)accelsensitivity; \r\n   dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;\r\n   dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;\r\n}\r\n\r\n   \r\n// Accelerometer and gyroscope self test; check calibration wrt factory settings\r\nvoid MPU9250SelfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass\r\n{\r\n   uint8_t rawData[6] = {0, 0, 0, 0, 0, 0};\r\n   uint8_t selfTest[6];\r\n   int16_t gAvg[3], aAvg[3], aSTAvg[3], gSTAvg[3];\r\n   float factoryTrim[6];\r\n   uint8_t FS = 0;\r\n   \r\n  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00);    // Set gyro sample rate to 1 kHz\r\n  writeByte(MPU9250_ADDRESS, CONFIG, 0x02);        // Set gyro sample rate to 1 kHz and DLPF to 92 Hz\r\n  writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 1<<FS);  // Set full scale range for the gyro to 250 dps\r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz\r\n  writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 1<<FS); // Set full scale range for the accelerometer to 2 g\r\n\r\n  for( int ii = 0; ii < 200; ii++) {  // get average current values of gyro and acclerometer\r\n  \r\n  readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]);        // Read the six raw data registers into data array\r\n  aAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  aAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;  \r\n  aAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \r\n  \r\n    readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);       // Read the six raw data registers sequentially into data array\r\n  gAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  gAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;  \r\n  gAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \r\n  }\r\n  \r\n  for (int ii =0; ii < 3; ii++) {  // Get average of 200 values and store as average current readings\r\n  aAvg[ii] /= 200;\r\n  gAvg[ii] /= 200;\r\n  }\r\n  \r\n// Configure the accelerometer for self-test\r\n   writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g\r\n   writeByte(MPU9250_ADDRESS, GYRO_CONFIG,  0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s\r\n   delay(25);  // Delay a while to let the device stabilize\r\n\r\n  for( int ii = 0; ii < 200; ii++) {  // get average self-test values of gyro and acclerometer\r\n  \r\n  readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers into data array\r\n  aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;  \r\n  aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \r\n  \r\n    readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);  // Read the six raw data registers sequentially into data array\r\n  gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ;  // Turn the MSB and LSB into a signed 16-bit value\r\n  gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;  \r\n  gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \r\n  }\r\n  \r\n  for (int ii =0; ii < 3; ii++) {  // Get average of 200 values and store as average self-test readings\r\n  aSTAvg[ii] /= 200;\r\n  gSTAvg[ii] /= 200;\r\n  }   \r\n  \r\n // Configure the gyro and accelerometer for normal operation\r\n   writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);  \r\n   writeByte(MPU9250_ADDRESS, GYRO_CONFIG,  0x00);  \r\n   delay(25);  // Delay a while to let the device stabilize\r\n   \r\n   // Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg\r\n   selfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel self-test results\r\n   selfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel self-test results\r\n   selfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel self-test results\r\n   selfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO);  // X-axis gyro self-test results\r\n   selfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO);  // Y-axis gyro self-test results\r\n   selfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO);  // Z-axis gyro self-test results\r\n\r\n  // Retrieve factory self-test value from self-test code reads\r\n   factoryTrim[0] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[0] - 1.0) )); // FT[Xa] factory trim calculation\r\n   factoryTrim[1] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[1] - 1.0) )); // FT[Ya] factory trim calculation\r\n   factoryTrim[2] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[2] - 1.0) )); // FT[Za] factory trim calculation\r\n   factoryTrim[3] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[3] - 1.0) )); // FT[Xg] factory trim calculation\r\n   factoryTrim[4] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[4] - 1.0) )); // FT[Yg] factory trim calculation\r\n   factoryTrim[5] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[5] - 1.0) )); // FT[Zg] factory trim calculation\r\n \r\n // Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response\r\n // To get percent, must multiply by 100\r\n   for (int i = 0; i < 3; i++) {\r\n     destination[i]   = 100.0*((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i];   // Report percent differences\r\n     destination[i+3] = 100.0*((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3]; // Report percent differences\r\n   }\r\n   \r\n}\r\n\r\n        \r\n        // Wire.h read and write protocols\r\n        void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)\r\n{\r\n  Wire.beginTransmission(address);  // Initialize the Tx buffer\r\n  Wire.write(subAddress);           // Put slave register address in Tx buffer\r\n  Wire.write(data);                 // Put data in Tx buffer\r\n  Wire.endTransmission();           // Send the Tx buffer\r\n}\r\n\r\n        uint8_t readByte(uint8_t address, uint8_t subAddress)\r\n{\r\n  uint8_t data; // `data` will store the register data   \r\n  Wire.beginTransmission(address);         // Initialize the Tx buffer\r\n  Wire.write(subAddress);                  // Put slave register address in Tx buffer\r\n  Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive\r\n  Wire.requestFrom(address, (uint8_t) 1);  // Read one byte from slave register address \r\n  data = Wire.read();                      // Fill Rx buffer with result\r\n  return data;                             // Return data read from slave register\r\n}\r\n\r\n        void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)\r\n{  \r\n  Wire.beginTransmission(address);   // Initialize the Tx buffer\r\n  Wire.write(subAddress);            // Put slave register address in Tx buffer\r\n  Wire.endTransmission(false);       // Send the Tx buffer, but send a restart to keep connection alive\r\n  uint8_t i = 0;\r\n        Wire.requestFrom(address, count);  // Read bytes from slave register address \r\n  while (Wire.available()) {\r\n        dest[i++] = Wire.read(); }         // Put read results in the Rx buffer\r\n}\r\n\r\n\r\nvoid MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)\r\n{\r\n  float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3];   // short name local variable for readability\r\n  float norm;\r\n  float hx, hy, _2bx, _2bz;\r\n  float s1, s2, s3, s4;\r\n  float qDot1, qDot2, qDot3, qDot4;\r\n\r\n  // Auxiliary variables to avoid repeated arithmetic\r\n  float _2q1mx;\r\n  float _2q1my;\r\n  float _2q1mz;\r\n  float _2q2mx;\r\n  float _4bx;\r\n  float _4bz;\r\n  float _2q1 = 2.0f * q1;\r\n  float _2q2 = 2.0f * q2;\r\n  float _2q3 = 2.0f * q3;\r\n  float _2q4 = 2.0f * q4;\r\n  float _2q1q3 = 2.0f * q1 * q3;\r\n  float _2q3q4 = 2.0f * q3 * q4;\r\n  float q1q1 = q1 * q1;\r\n  float q1q2 = q1 * q2;\r\n  float q1q3 = q1 * q3;\r\n  float q1q4 = q1 * q4;\r\n  float q2q2 = q2 * q2;\r\n  float q2q3 = q2 * q3;\r\n  float q2q4 = q2 * q4;\r\n  float q3q3 = q3 * q3;\r\n  float q3q4 = q3 * q4;\r\n  float q4q4 = q4 * q4;\r\n\r\n  // Normalise accelerometer measurement\r\n  norm = sqrt(ax * ax + ay * ay + az * az);\r\n  if (norm == 0.0f) return; // handle NaN\r\n  norm = 1.0f/norm;\r\n  ax *= norm;\r\n  ay *= norm;\r\n  az *= norm;\r\n\r\n  // Normalise magnetometer measurement\r\n  norm = sqrt(mx * mx + my * my + mz * mz);\r\n  if (norm == 0.0f) return; // handle NaN\r\n  norm = 1.0f/norm;\r\n  mx *= norm;\r\n  my *= norm;\r\n  mz *= norm;\r\n\r\n  // Reference direction of Earth's magnetic field\r\n  _2q1mx = 2.0f * q1 * mx;\r\n  _2q1my = 2.0f * q1 * my;\r\n  _2q1mz = 2.0f * q1 * mz;\r\n  _2q2mx = 2.0f * q2 * mx;\r\n  hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;\r\n  hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;\r\n  _2bx = sqrt(hx * hx + hy * hy);\r\n  _2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;\r\n  _4bx = 2.0f * _2bx;\r\n  _4bz = 2.0f * _2bz;\r\n\r\n  // Gradient decent algorithm corrective step\r\n  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);\r\n  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);\r\n  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);\r\n  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);\r\n  norm = sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4);    // normalise step magnitude\r\n  norm = 1.0f/norm;\r\n  s1 *= norm;\r\n  s2 *= norm;\r\n  s3 *= norm;\r\n  s4 *= norm;\r\n\r\n  // Compute rate of change of quaternion\r\n  qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;\r\n  qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;\r\n  qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;\r\n  qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;\r\n\r\n  // Integrate to yield quaternion\r\n  q1 += qDot1 * deltat;\r\n  q2 += qDot2 * deltat;\r\n  q3 += qDot3 * deltat;\r\n  q4 += qDot4 * deltat;\r\n  norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);    // normalise quaternion\r\n  norm = 1.0f/norm;\r\n  q[0] = q1 * norm;\r\n  q[1] = q2 * norm;\r\n  q[2] = q3 * norm;\r\n  q[3] = q4 * norm;\r\n\r\n}\r\n\r\n\r\n\r\n// Similar to Madgwick scheme but uses proportional and integral filtering on the error between estimated reference vectors and\r\n// measured ones.\r\nvoid MahonyQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)\r\n{\r\n  float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3];   // short name local variable for readability\r\n  float norm;\r\n  float hx, hy, bx, bz;\r\n  float vx, vy, vz, wx, wy, wz;\r\n  float ex, ey, ez;\r\n  float pa, pb, pc;\r\n\r\n  // Auxiliary variables to avoid repeated arithmetic\r\n  float q1q1 = q1 * q1;\r\n  float q1q2 = q1 * q2;\r\n  float q1q3 = q1 * q3;\r\n  float q1q4 = q1 * q4;\r\n  float q2q2 = q2 * q2;\r\n  float q2q3 = q2 * q3;\r\n  float q2q4 = q2 * q4;\r\n  float q3q3 = q3 * q3;\r\n  float q3q4 = q3 * q4;\r\n  float q4q4 = q4 * q4;\r\n\r\n  // Normalise accelerometer measurement\r\n  norm = sqrt(ax * ax + ay * ay + az * az);\r\n  if (norm == 0.0f) return; // handle NaN\r\n  norm = 1.0f / norm;        // use reciprocal for division\r\n  ax *= norm;\r\n  ay *= norm;\r\n  az *= norm;\r\n\r\n  // Normalise magnetometer measurement\r\n  norm = sqrt(mx * mx + my * my + mz * mz);\r\n  if (norm == 0.0f) return; // handle NaN\r\n  norm = 1.0f / norm;        // use reciprocal for division\r\n  mx *= norm;\r\n  my *= norm;\r\n  mz *= norm;\r\n\r\n  // Reference direction of Earth's magnetic field\r\n  hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);\r\n  hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);\r\n  bx = sqrt((hx * hx) + (hy * hy));\r\n  bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);\r\n\r\n  // Estimated direction of gravity and magnetic field\r\n  vx = 2.0f * (q2q4 - q1q3);\r\n  vy = 2.0f * (q1q2 + q3q4);\r\n  vz = q1q1 - q2q2 - q3q3 + q4q4;\r\n  wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);\r\n  wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);\r\n  wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);\r\n\r\n  // Error is cross product between estimated direction and measured direction of gravity\r\n  ex = (ay * vz - az * vy) + (my * wz - mz * wy);\r\n  ey = (az * vx - ax * vz) + (mz * wx - mx * wz);\r\n  ez = (ax * vy - ay * vx) + (mx * wy - my * wx);\r\n  if (Ki > 0.0f)\r\n  {\r\n    eInt[0] += ex;      // accumulate integral error\r\n    eInt[1] += ey;\r\n    eInt[2] += ez;\r\n  }\r\n  else\r\n  {\r\n    eInt[0] = 0.0f;     // prevent integral wind up\r\n    eInt[1] = 0.0f;\r\n    eInt[2] = 0.0f;\r\n  }\r\n\r\n  // Apply feedback terms\r\n  gx = gx + Kp * ex + Ki * eInt[0];\r\n  gy = gy + Kp * ey + Ki * eInt[1];\r\n  gz = gz + Kp * ez + Ki * eInt[2];\r\n\r\n  // Integrate rate of change of quaternion\r\n  pa = q2;\r\n  pb = q3;\r\n  pc = q4;\r\n  q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);\r\n  q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);\r\n  q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);\r\n  q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);\r\n\r\n  // Normalise quaternion\r\n  norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);\r\n  norm = 1.0f / norm;\r\n  q[0] = q1 * norm;\r\n  q[1] = q2 * norm;\r\n  q[2] = q3 * norm;\r\n  q[3] = q4 * norm;\r\n  \r\n}\r\n\r\n"},"comment":{"url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/comments/143318012","html_url":"https://github.com/kriswiner/MPU-9250/issues/22#issuecomment-143318012","issue_url":"https://api.github.com/repos/kriswiner/MPU-9250/issues/22","id":143318012,"user":{"login":"kriswiner","id":6698410,"avatar_url":"https://avatars.githubusercontent.com/u/6698410?v=3","gravatar_id":"","url":"https://api.github.com/users/kriswiner","html_url":"https://github.com/kriswiner","followers_url":"https://api.github.com/users/kriswiner/followers","following_url":"https://api.github.com/users/kriswiner/following{/other_user}","gists_url":"https://api.github.com/users/kriswiner/gists{/gist_id}","starred_url":"https://api.github.com/users/kriswiner/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/kriswiner/subscriptions","organizations_url":"https://api.github.com/users/kriswiner/orgs","repos_url":"https://api.github.com/users/kriswiner/repos","events_url":"https://api.github.com/users/kriswiner/events{/privacy}","received_events_url":"https://api.github.com/users/kriswiner/received_events","type":"User","site_admin":false},"created_at":"2015-09-25T18:40:41Z","updated_at":"2015-09-25T18:40:41Z","body":"Hi Navid,\n\nI'm not sure what you mean by \"The problem is when I Serial.Print (pitch,\nyaw, roll) after a certain angle they become unstable and they interfere\nwith each other.\"\n\nThese are not independent; Euler angles will be wrong at high angles, that's\nwhy the quaternion is the more fundamental measure of orientation. But\nusually if you change heading, you should get a sensible result like with a\ncompass. Is this not the case?\n\nKris\n\n-----Original Message-----\nFrom: Navid360 [mailto:notifications@github.com] \nSent: September 25, 2015 11:32 AM\nTo: kriswiner/MPU-9250\nSubject: [MPU-9250] pitch, yaw, roll Interrupting each other! (#22)\n\nHi Kris\nI am running the attached code on a Teensy3.1 and a cheap MPU9250 \n(http://www.ebay.com/itm/SPI-IIC-MPU-9250-9-Axis-Attitude-Gyro-Accelerator-M\nagnetometer-Sensor-Module-/131185485892)\n\nI plotted raw data in Matlab and accelerometer,gyro, and magnetometer are\nall calibrated, The problem is when I Serial.Print (pitch, yaw, roll) after\na certain angle they become unstable and they interfere with each other. I\nam using madwick algorithm as you can see in my code.\n\nWould you please let me know what is wrong with it?\n\nThanks\nNavid\n\nHere is my Code: \n\n/* MPU9250 Basic Example Code\nby: Kris Winer\ndate: April 1, 2014\nlicense: Beerware - Use this code however you'd like. If you \nfind it useful you can buy me a beer some time.\n\nDemonstrate basic MPU-9250 functionality including parameterizing the\nregister addresses, initializing the sensor, \ngetting properly scaled accelerometer, gyroscope, and magnetometer data out.\nAdded display functions to \nallow display to on breadboard monitor. Addition of 9 DoF sensor fusion\nusing open source Madgwick and \nMahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the\nTeensy 3.1.\n\nSDA and SCL should have external pull-up resistors (to 3.3V).\n10k resistors are on the EMSENSR-9250 breakout board.\n\nHardware setup:\nMPU9250 Breakout --------- Arduino\nVDD ---------------------- 3.3V\nVDDI --------------------- 3.3V\nSDA ----------------------- A4\nSCL ----------------------- A5\nGND ---------------------- GND\n\nNote: The MPU9250 is an I2C sensor and uses the Arduino Wire library. \nBecause the sensor is not 5V tolerant, we are using a 3.3 V 8 MHz Pro Mini\nor a 3.3 V Teensy 3.1.\nWe have disabled the internal pull-ups used by the Wire library in the\nWire.h/twi.c utility file.\nWe are also using the 400 kHz fast I2C mode by setting the TWI_FREQ to\n400000L /twi.h utility file.\n*/\n#include \n#include \n\n// See also MPU-9250 Register Map and Descriptions, Revision 4.0,\nRM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in \n// above document; the MPU9250 and MPU9150 are virtually identical but the\nlatter has a different register map\n//\n//Magnetometer Registers\n#define AK8963_ADDRESS 0x0C\n#define WHO_AM_I_AK8963 0x00 // should return 0x48\n#define INFO 0x01\n#define AK8963_ST1 0x02 // data ready status bit 0\n#define AK8963_XOUT_L 0x03 // data\n#define AK8963_XOUT_H 0x04\n#define AK8963_YOUT_L 0x05\n#define AK8963_YOUT_H 0x06\n#define AK8963_ZOUT_L 0x07\n#define AK8963_ZOUT_H 0x08\n#define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status\nbit 2\n#define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001),\nself-test (1000) and Fuse ROM (1111) modes on bits 3:0\n#define AK8963_ASTC 0x0C // Self test control\n#define AK8963_I2CDIS 0x0F // I2C disable\n#define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value\n#define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value\n#define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value\n\n#define SELF_TEST_X_GYRO 0x00\n\n#define SELF_TEST_Y_GYRO 0x01\n\n#define SELF_TEST_Z_GYRO 0x02\n\n/*#define X_FINE_GAIN 0x03 // [7:0] fine gain\n#define Y_FINE_GAIN 0x04\n#define Z_FINE_GAIN 0x05\n#define XA_OFFSET_H 0x06 // User-defined trim values for accelerometer\n#define XA_OFFSET_L_TC 0x07\n#define YA_OFFSET_H 0x08\n#define YA_OFFSET_L_TC 0x09\n#define ZA_OFFSET_H 0x0A\n#define ZA_OFFSET_L_TC 0x0B */\n\n#define SELF_TEST_X_ACCEL 0x0D\n#define SELF_TEST_Y_ACCEL 0x0E\n\n#define SELF_TEST_Z_ACCEL 0x0F\n\n#define SELF_TEST_A 0x10\n\n#define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope\n#define XG_OFFSET_L 0x14\n#define YG_OFFSET_H 0x15\n#define YG_OFFSET_L 0x16\n#define ZG_OFFSET_H 0x17\n#define ZG_OFFSET_L 0x18\n#define SMPLRT_DIV 0x19\n#define CONFIG 0x1A\n#define GYRO_CONFIG 0x1B\n#define ACCEL_CONFIG 0x1C\n#define ACCEL_CONFIG2 0x1D\n#define LP_ACCEL_ODR 0x1E\n\n#define WOM_THR 0x1F \n\n#define MOT_DUR 0x20 // Duration counter threshold for motion interrupt\ngeneration, 1 kHz rate, LSB = 1 ms\n#define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0]\n#define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion\ninterrupt generation, 16 Hz rate, LSB = 64 ms\n\n#define FIFO_EN 0x23\n#define I2C_MST_CTRL 0x24\n\n#define I2C_SLV0_ADDR 0x25\n#define I2C_SLV0_REG 0x26\n#define I2C_SLV0_CTRL 0x27\n#define I2C_SLV1_ADDR 0x28\n#define I2C_SLV1_REG 0x29\n#define I2C_SLV1_CTRL 0x2A\n#define I2C_SLV2_ADDR 0x2B\n#define I2C_SLV2_REG 0x2C\n#define I2C_SLV2_CTRL 0x2D\n#define I2C_SLV3_ADDR 0x2E\n#define I2C_SLV3_REG 0x2F\n#define I2C_SLV3_CTRL 0x30\n#define I2C_SLV4_ADDR 0x31\n#define I2C_SLV4_REG 0x32\n#define I2C_SLV4_DO 0x33\n#define I2C_SLV4_CTRL 0x34\n#define I2C_SLV4_DI 0x35\n#define I2C_MST_STATUS 0x36\n#define INT_PIN_CFG 0x37\n#define INT_ENABLE 0x38\n#define DMP_INT_STATUS 0x39 // Check DMP interrupt\n#define INT_STATUS 0x3A\n#define ACCEL_XOUT_H 0x3B\n#define ACCEL_XOUT_L 0x3C\n#define ACCEL_YOUT_H 0x3D\n#define ACCEL_YOUT_L 0x3E\n#define ACCEL_ZOUT_H 0x3F\n#define ACCEL_ZOUT_L 0x40\n#define TEMP_OUT_H 0x41\n#define TEMP_OUT_L 0x42\n#define GYRO_XOUT_H 0x43\n#define GYRO_XOUT_L 0x44\n#define GYRO_YOUT_H 0x45\n#define GYRO_YOUT_L 0x46\n#define GYRO_ZOUT_H 0x47\n#define GYRO_ZOUT_L 0x48\n#define EXT_SENS_DATA_00 0x49\n#define EXT_SENS_DATA_01 0x4A\n#define EXT_SENS_DATA_02 0x4B\n#define EXT_SENS_DATA_03 0x4C\n#define EXT_SENS_DATA_04 0x4D\n#define EXT_SENS_DATA_05 0x4E\n#define EXT_SENS_DATA_06 0x4F\n#define EXT_SENS_DATA_07 0x50\n#define EXT_SENS_DATA_08 0x51\n#define EXT_SENS_DATA_09 0x52\n#define EXT_SENS_DATA_10 0x53\n#define EXT_SENS_DATA_11 0x54\n#define EXT_SENS_DATA_12 0x55\n#define EXT_SENS_DATA_13 0x56\n#define EXT_SENS_DATA_14 0x57\n#define EXT_SENS_DATA_15 0x58\n#define EXT_SENS_DATA_16 0x59\n#define EXT_SENS_DATA_17 0x5A\n#define EXT_SENS_DATA_18 0x5B\n#define EXT_SENS_DATA_19 0x5C\n#define EXT_SENS_DATA_20 0x5D\n#define EXT_SENS_DATA_21 0x5E\n#define EXT_SENS_DATA_22 0x5F\n#define EXT_SENS_DATA_23 0x60\n#define MOT_DETECT_STATUS 0x61\n#define I2C_SLV0_DO 0x63\n#define I2C_SLV1_DO 0x64\n#define I2C_SLV2_DO 0x65\n#define I2C_SLV3_DO 0x66\n#define I2C_MST_DELAY_CTRL 0x67\n#define SIGNAL_PATH_RESET 0x68\n#define MOT_DETECT_CTRL 0x69\n#define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP\n#define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode\n#define PWR_MGMT_2 0x6C\n#define DMP_BANK 0x6D // Activates a specific bank in the DMP\n#define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start\naddress in specified DMP bank\n#define DMP_REG 0x6F // Register in DMP from which to read or to which to\nwrite\n#define DMP_REG_1 0x70\n#define DMP_REG_2 0x71 \n#define FIFO_COUNTH 0x72\n#define FIFO_COUNTL 0x73\n#define FIFO_R_W 0x74\n#define WHO_AM_I_MPU9250 0x75 // Should return 0x71\n#define XA_OFFSET_H 0x77\n#define XA_OFFSET_L 0x78\n#define YA_OFFSET_H 0x7A\n#define YA_OFFSET_L 0x7B\n#define ZA_OFFSET_H 0x7D\n#define ZA_OFFSET_L 0x7E\n\n// Using the MSENSR-9250 breakout board, ADO is set to 0 \n// Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1\n#define ADO 1\n#if ADO\n#define MPU9250_ADDRESS 0x68 // Device address when ADO = 1\n#else\n#define MPU9250_ADDRESS 0x69 // Device address when ADO = 0\n#define AK8963_ADDRESS 0x0C // Address of magnetometer\n#endif \n\n#define AHRS true // set to false for basic data read\n#define SerialDebug true // set to true to get Serial output for debugging\n\n// Set initial input parameters\nenum Ascale {\nAFS_2G = 0,\nAFS_4G,\nAFS_8G,\nAFS_16G\n};\n\nenum Gscale {\nGFS_250DPS = 0,\nGFS_500DPS,\nGFS_1000DPS,\nGFS_2000DPS\n};\n\nenum Mscale {\nMFS_14BITS = 0, // 0.6 mG per LSB\nMFS_16BITS // 0.15 mG per LSB\n};\n\n// Specify sensor full scale\nuint8_t Gscale = GFS_250DPS;\nuint8_t Ascale = AFS_2G;\nuint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer\nresolution\nuint8_t Mmode = 0x02; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer\ndata read\nfloat aRes, gRes, mRes; // scale resolutions per LSB for the sensors\n\n// Pin definitions\nint intPin = 12; // These can be changed, 2 and 3 are the Arduinos ext int\npins\nint myLed = 13; // Set up pin 13 led for toggling\n\nint16_t accelCount[3]; // Stores the 16-bit signed accelerometer sensor\noutput\nint16_t gyroCount[3]; // Stores the 16-bit signed gyro sensor output\nint16_t magCount[3]; // Stores the 16-bit signed magnetometer sensor output\nfloat magCalibration[3] = {0, 0, 0}, magbias[3] = {0, 0, 0}; // Factory mag\ncalibration and mag bias\nfloat gyroBias[3] = {0, 0, 0}, accelBias[3] = {0, 0, 0}; // Bias corrections\nfor gyro and accelerometer\nint16_t tempCount; // temperature raw count output\nfloat temperature; // Stores the real internal chip temperature in degrees\nCelsius\nfloat SelfTest[6]; // holds results of gyro and accelerometer self test\n\n// global constants for 9 DoF fusion and AHRS (Attitude and Heading\nReference System)\nfloat GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error\nin rads/s (start at 40 deg/s)\nfloat GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift\nin rad/s/s (start at 0.0 deg/s/s)\n// There is a tradeoff in the beta parameter between accuracy and response\nspeed.\n// In the original Madgwick study, beta of 0.041 (corresponding to\nGyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.\n// However, with this value, the LSM9SD0 response time is about 10 seconds\nto a stable initial quaternion.\n// Subsequent changes also require a longish lag time to a stable output,\nnot fast enough for a quadcopter or robot car!\n// By increasing beta (GyroMeasError) by about a factor of fifteen, the\nresponse time constant is reduced to ~2 sec\n// I haven't noticed any reduction in solution accuracy. This is essentially\nthe I coefficient in a PID control sense; \n// the bigger the feedback coefficient, the faster the solution converges,\nusually at the expense of accuracy. \n// In any case, this is the free parameter in the Madgwick filtering and\nfusion scheme.\nfloat beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta\nfloat zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other\nfree parameter in the Madgwick scheme usually set to a small or zero value\n#define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter\nand fusion scheme, Kp for proportional feedback, Ki for integral\n#define Ki 0.0f\n\nuint32_t delt_t = 0; // used to control display output rate\nuint32_t count = 0, sumCount = 0; // used to control display output rate\nfloat pitch, yaw, roll;\nfloat deltat = 0.0f, sum = 0.0f; // integration interval for both filter\nschemes\nuint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration\ninterval\nuint32_t Now = 0; // used to calculate integration interval\n\nfloat ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor\ndata values \nfloat q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion\nfloat eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for\nMahony method\n\nvoid setup()\n{\nWire.begin();\n// TWBR = 12; // 400 kbit/sec I2C speed\nSerial.begin(115200);\n\n// Set up the interrupt pin, its set as active high, push-pull\npinMode(intPin, INPUT);\ndigitalWrite(intPin, LOW);\npinMode(myLed, OUTPUT);\ndigitalWrite(myLed, HIGH);\n\ndelay(1000);\n\n// Read the WHO_AM_I register, this is a good test of communication\nbyte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I\nregister for MPU-9250\n\ndelay(1000); \n\nif (c == 0x71) // WHO_AM_I should always be 0x68\n{ \n\nMPU9250SelfTest(SelfTest); // Start by performing self test and reporting\nvalues\n\ncalibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers,\nload biases in bias registers\n\n\ndelay(1000); \n\ninitMPU9250(); \n\n\n// Serial.println(\"MPU9250 initialized for active data mode....\"); //\nInitialize device for active mode read of acclerometer, gyroscope, and\ntemperature\n\n// Read the WHO_AM_I register of the magnetometer, this is a good test of\ncommunication\nbyte d = readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);  // Read WHO_AM_I\nregister for AK8963\n\ndelay(1000); \n\n// Get magnetometer calibration from AK8963 ROM\ninitAK8963(magCalibration); //Serial.println(\"AK8963 initialized for active\ndata mode....\"); // Initialize device for active mode read of magnetometer\n\n\n\n\ndelay(1000);  \n\n\n}\nelse\n{\n// Serial.print(\"Could not connect to MPU9250: 0x\");\n// Serial.println(c, HEX);\nwhile(1) ; // Loop forever if communication doesn't happen\n}\n}\n\nvoid loop()\n{\n\n// If intPin goes high, all data registers have new data\nif (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) { // On interrupt, check\nif data ready interrupt\nreadAccelData(accelCount); // Read the x/y/z adc values\ngetAres();\n\n// Now we'll calculate the accleration value into actual g's\nax = (float)accelCount[0]*aRes; // - accelBias[0];  // get actual g value,\nthis depends on scale being set\nay = (float)accelCount[1]*aRes; // - accelBias[1];   \naz = (float)accelCount[2]*aRes; // - accelBias[2];  \n\nreadGyroData(gyroCount);  // Read the x/y/z adc values\ngetGres();\n\n// Calculate the gyro value into actual degrees per second\ngx = (float)gyroCount[0]*gRes;  // get actual gyro value, this depends on\nscale being set\ngy = (float)gyroCount[1]*gRes;  \ngz = (float)gyroCount[2]*gRes;   \n\nreadMagData(magCount);  // Read the x/y/z adc values\ngetMres();\nmagbias[0] = +281.;  // User environmental x-axis correction in milliGauss,\nshould be automatically calculated\nmagbias[1] = +231.;  // User environmental x-axis correction in milliGauss\nmagbias[2] = -406.;  // User environmental x-axis correction in milliGauss\n\n// Calculate the magnetometer values in milliGauss\n// Include factory calibration per data sheet and user environmental\ncorrections\nmx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0];  // get actual\nmagnetometer value, this depends on scale being set\nmy = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];  \nmz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2]; \n\n\n    ax=ax-850/1000;\nay=ay-850/1000;\naz=az+500/1000;\n\n\n}\n\nNow = micros();\ndeltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time\nelapsed since last filter update\nlastUpdate = Now;\n\nsum += deltat; // sum for averaging filter update rate\nsumCount++;\n\n// Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of\nthe magnetometer;\n// the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of\naccelerometer and gyro!\n// We have to make some allowance for this orientationmismatch in feeding\nthe output to the quaternion filter.\n// For the MPU-9250, we have chosen a magnetic rotation that keeps the\nsensor forward along the x-axis just like\n// in the LSM9DS0 sensor. This rotation can be modified to allow any\nconvenient orientation convention.\n// This is ok by aircraft orientation standards!\n\n// Pass gyro rate as rad/s\nMadgwickQuaternionUpdate(ax, ay, az, gxPI/180.0f, gyPI/180.0f, gzPI/180.0f,\nmy, mx, mz);\n//MahonyQuaternionUpdate(ax, ay, az, gxPI/180.0f, gyPI/180.0f, gzPI/180.0f,\nmy, mx, mz);\n\n// Serial print and/or display at 0.5 s rate independent of data rates\ndelt_t = millis() - count;\nif (delt_t > 50) { // update LCD once per half-second independent of read\nrate\n\nif(SerialDebug) {\n\n\n// Define output variables from updated quaternion---these are Tait-Bryan\nangles, commonly used in aircraft orientation.\n// In this coordinate system, the positive z-axis is down toward Earth. \n// Yaw is the angle between Sensor x-axis and Earth magnetic North (or true\nNorth if corrected for local declination, looking down on the sensor\npositive yaw is counterclockwise.\n// Pitch is angle between sensor x-axis and Earth ground plane, toward the\nEarth is positive, up toward the sky is negative.\n// Roll is angle between sensor y-axis and Earth ground plane, y-axis up is\npositive roll.\n// These arise from the definition of the homogeneous rotation matrix\nconstructed from quaternions.\n// Tait-Bryan angles as well as Euler angles are non-commutative; that is,\nthe get the correct orientation the rotations must be\n// applied in the correct order which for this configuration is yaw, pitch,\nand then roll.\n// For more see\nhttp://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\nwhich has additional links.\nyaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] -\nq[2] * q[2] - q[3] * q[3]);\n\npitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));\nroll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] -\nq[2] * q[2] + q[3] * q[3]);\npitch *= 180.0f / PI;\nyaw *= 180.0f / PI; \n//yaw -= 13.8; // Declination at Danville, California is 13 degrees 48\nminutes and 47 seconds on 2014-04-04\nroll *= 180.0f / PI;\n\nif(SerialDebug) {\n//Serial.print(\"Yaw, Pitch, Roll: \");\nint sensorvalue = analogRead (A2);\n\n\nSerial.print(sensorvalue);\nSerial.print(\"\\t\");\nSerial.print(yaw, 2);\nSerial.print(\"\\t\");\nSerial.print(pitch, 2);\nSerial.print(\"\\t\");\nSerial.println(roll, 2);\n\n//Serial.print(\"rate = \"); Serial.print((float)sumCount/sum, 2);\nSerial.println(\" Hz\");\n}\n\n\n\n// With these settings the filter is updating at a ~145 Hz rate using the\nMadgwick scheme and \n// >200 Hz using the Mahony scheme even though the display refreshes at only\n2 Hz.\n// The filter update rate is determined mostly by the mathematical steps in\nthe respective algorithms, \n// the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer\nODR:\n// an ODR of 10 Hz for the magnetometer produce the above rates, maximum\nmagnetometer ODR of 100 Hz produces\n// filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony\nschemes, respectively. \n// This is presumably because the magnetometer read takes longer than the\ngyro or accelerometer reads.\n// This filter update rate should be fast enough to maintain accurate\nplatform orientation for \n// stabilization control of a fast-moving robot or quadcopter. Compare to\nthe update rate of 200 Hz\n// produced by the on-board Digital Motion Processor of Invensense's MPU6050\n6 DoF and MPU9150 9DoF sensors.\n// The 3.3 V 8 MHz Pro Mini is doing pretty well!\n//display.setCursor(0, 40); display.print(\"rt: \"); display.print((float)\nsumCount / sum, 2); display.print(\" Hz\"); \n//display.display();\n\ncount = millis(); \nsumCount = 0;\nsum = 0;    \n}\n}\n\n\n}\n\n//==========================================================================\n=========================================\n//====== Set of useful function to access acceleration. gyroscope,\nmagnetometer, and temperature data\n//==========================================================================\n=========================================\n\nvoid getMres() {\nswitch (Mscale)\n{\n// Possible magnetometer scales (and their register bit settings) are:\n// 14 bit resolution (0) and 16 bit resolution (1)\ncase MFS_14BITS:\nmRes = 10.4912./8190.; // Proper scale to return milliGauss\nbreak;\ncase MFS_16BITS:\nmRes = 10.4912./32760.0; // Proper scale to return milliGauss\nbreak;\n}\n}\n\nvoid getGres() {\nswitch (Gscale)\n{\n// Possible gyro scales (and their register bit settings) are:\n// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11). \n// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that\n2-bit value:\ncase GFS_250DPS:\ngRes = 250.0/32768.0;\nbreak;\ncase GFS_500DPS:\ngRes = 500.0/32768.0;\nbreak;\ncase GFS_1000DPS:\ngRes = 1000.0/32768.0;\nbreak;\ncase GFS_2000DPS:\ngRes = 2000.0/32768.0;\nbreak;\n}\n}\n\nvoid getAres() {\nswitch (Ascale)\n{\n// Possible accelerometer scales (and their register bit settings) are:\n// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11). \n// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that\n2-bit value:\ncase AFS_2G:\naRes = 2.0/32768.0;\nbreak;\ncase AFS_4G:\naRes = 4.0/32768.0;\nbreak;\ncase AFS_8G:\naRes = 8.0/32768.0;\nbreak;\ncase AFS_16G:\naRes = 16.0/32768.0;\nbreak;\n}\n}\n\nvoid readAccelData(int16_t * destination)\n{\nuint8_t rawData[6]; // x/y/z accel register data stored here\nreadBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six\nraw data registers into data array\ndestination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB\nand LSB into a signed 16-bit value\ndestination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;\n\ndestination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; \n}\n\nvoid readGyroData(int16_t * destination)\n{\nuint8_t rawData[6]; // x/y/z gyro register data stored here\nreadBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw\ndata registers sequentially into data array\ndestination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB\nand LSB into a signed 16-bit value\ndestination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;\n\ndestination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ; \n}\n\nvoid readMagData(int16_t * destination)\n{\nuint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here,\nmust read ST2 at end of data acquisition\nif(readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01) { // wait for magnetometer\ndata ready bit to be set\nreadBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]); // Read the six\nraw data and ST2 registers sequentially into data array\nuint8_t c = rawData[6]; // End data read by reading ST2 register\nif(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then\nreport data\ndestination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB\nand LSB into a signed 16-bit value\ndestination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as\nlittle Endian\ndestination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ; \n}\n}\n}\n\nint16_t readTempData()\n{\nuint8_t rawData[2]; // x/y/z gyro register data stored here\nreadBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw\ndata registers sequentially into data array \nreturn ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB\ninto a 16-bit value\n}\n\nvoid initAK8963(float * destination)\n{\n// First extract the factory calibration for each magnetometer axis\nuint8_t rawData[3]; // x/y/z gyro calibration data stored here\nwriteByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer\n\ndelay(10);\nwriteByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode\ndelay(10);\nreadBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]); // Read the x-, y-,\nand z-axis calibration values\ndestination[0] = (float)(rawData[0] - 128)/256. + 1.; // Return x-axis\nsensitivity adjustment values, etc.\ndestination[1] = (float)(rawData[1] - 128)/256. + 1.;\n\ndestination[2] = (float)(rawData[2] - 128)/256. + 1.; \nwriteByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer\n\ndelay(10);\n// Configure the magnetometer for continuous read and highest resolution\n// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL\nregister,\n// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for\n8 Hz and 0110 for 100 Hz sample rates\nwriteByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set\nmagnetometer data resolution and sample ODR\ndelay(10);\n}\n\nvoid initMPU9250()\n{\n\n// wake up device\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6),\nenable all sensors \ndelay(100); // Wait for all registers to reset \n\n// get stable time source\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // Auto select clock source to\nbe PLL gyroscope reference if ready else\ndelay(200); \n\n// Configure Gyro and Thermometer\n// Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz,\nrespectively; \n// minimum delay time for this setting is 5.9 ms, which means sensor fusion\nupdate rates cannot\n// be higher than 1 / 0.0059 = 170 Hz\n// DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for\nboth\n// With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!),\n8 kHz, or 1 kHz\nwriteByte(MPU9250_ADDRESS, CONFIG, 0x03); \n\n// Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)\nwriteByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; a rate\nconsistent with the filter update rate \n// determined inset in CONFIG above\n\n// Set gyroscope full scale range\n// Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are\nleft-shifted into positions 4:3\nuint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG);\n// writeRegister(GYRO_CONFIG, c & ~0xE0); // Clear self-test bits [7:5] \nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x02); // Clear Fchoice bits\n[1:0] \nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]\nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, c | Gscale << 3); // Set full scale\nrange for the gyro\n// writeRegister(GYRO_CONFIG, c | 0x00); // Set Fchoice for the gyro to 11\nby writing its inverse to bits 1:0 of GYRO_CONFIG\n\n// Set accelerometer full-scale range configuration\nc = readByte(MPU9250_ADDRESS, ACCEL_CONFIG);\n// writeRegister(ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5] \nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, c | Ascale << 3); // Set full scale\nrange for the accelerometer \n\n// Set accelerometer sample rate configuration\n// It is possible to get a 4 kHz sample rate from the accelerometer by\nchoosing 1 for\n// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz\nc = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2);\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c & ~0x0F); // Clear\naccel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])\n\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c | 0x03); // Set accelerometer\nrate to 1 kHz and bandwidth to 41 Hz\n\n// The accelerometer, gyro, and thermometer are set to 1 kHz sample rates, \n// but all these rates are further reduced by a factor of 5 to 200 Hz\nbecause of the SMPLRT_DIV setting\n\n// Configure Interrupts and Bypass Enable\n// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH\nuntil interrupt cleared,\n// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips\n\n// can join the I2C bus and all can be controlled by the Arduino as master\nwriteByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x22);\n\nwriteByte(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0)\ninterrupt\ndelay(100);\n}\n\n// Function which accumulates gyro and accelerometer data after device\ninitialization. It calculates the average\n// of the at-rest readings and then loads the resulting offsets into\naccelerometer and gyro bias registers.\nvoid calibrateMPU9250(float * dest1, float * dest2)\n{\n\nuint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data\nuint16_t ii, packet_count, fifo_count;\nint32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0};\n\n// reset device\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset\nbit; toggle reset device\ndelay(100);\n\n// get stable time source; Auto select clock source to be PLL gyroscope\nreference if ready \n// else use the internal oscillator, bits 2:0 = 001\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);\n\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);\ndelay(200); \n\n// Configure device for bias calculation\nwriteByte(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts\nwriteByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO\nwriteByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock\nsource\nwriteByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master\nwriteByte(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master\nmodes\nwriteByte(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP\ndelay(15);\n\n// Configure MPU6050 gyro and accelerometer for bias calculation\nwriteByte(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz\nwriteByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz\nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250\ndegrees per second, maximum sensitivity\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer\nfull-scale to 2 g, maximum sensitivity\n\nuint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec\nuint16_t accelsensitivity = 16384; // = 16384 LSB/g\n\n// Configure FIFO to capture accelerometer and gyro data for bias\ncalculation\n\n\nwriteByte(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO\n\nwriteByte(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer\nsensors for FIFO (max size 512 bytes in MPU-9150)\ndelay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes\n\n// At end of sample accumulation, turn off FIFO sensor read\nwriteByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer\nsensors for FIFO\nreadBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample\ncount\nfifo_count = ((uint16_t)data[0] << 8) | data[1];\npacket_count = fifo_count/12;// How many sets of full gyro and accelerometer\ndata for averaging\n\nfor (ii = 0; ii < packet_count; ii++) {\nint16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};\nreadBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for\naveraging\naccel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form\nsigned 16-bit integer for each sample in FIFO\naccel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ;\naccel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ;\n\ngyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ;\ngyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ;\ngyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;\n\naccel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit\nbiases to get accumulated signed 32-bit biases\naccel_bias[1] += (int32_t) accel_temp[1];\naccel_bias[2] += (int32_t) accel_temp[2];\ngyro_bias[0]  += (int32_t) gyro_temp[0];\ngyro_bias[1]  += (int32_t) gyro_temp[1];\ngyro_bias[2]  += (int32_t) gyro_temp[2];\n\n\n}\naccel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average\ncount biases\naccel_bias[1] /= (int32_t) packet_count;\naccel_bias[2] /= (int32_t) packet_count;\ngyro_bias[0] /= (int32_t) packet_count;\ngyro_bias[1] /= (int32_t) packet_count;\ngyro_bias[2] /= (int32_t) packet_count;\n\nif(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} //\nRemove gravity from the z-axis accelerometer bias calculation\nelse {accel_bias[2] += (int32_t) accelsensitivity;}\n\n// Construct the gyro biases for push to the hardware gyro bias registers,\nwhich are reset to zero upon device startup\ndata[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per\ndeg/s to conform to expected bias input format\ndata[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign\non calculated average gyro biases\ndata[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;\ndata[3] = (-gyro_bias[1]/4) & 0xFF;\ndata[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;\ndata[5] = (-gyro_bias[2]/4) & 0xFF;\n\n// Push gyro biases to hardware registers\nwriteByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);\nwriteByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);\nwriteByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);\nwriteByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);\nwriteByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);\nwriteByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);\n\n// Output scaled gyro biases for display in the main program\ndest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;\n\ndest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;\ndest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;\n\n// Construct the accelerometer biases for push to the hardware accelerometer\nbias registers. These registers contain\n// factory trim values which must be added to the calculated accelerometer\nbiases; on boot up these registers will hold\n// non-zero values. In addition, bit 0 of the lower byte must be preserved\nsince it is used for temperature\n// compensation calculations. Accelerometer bias registers expect bias input\nas 2048 LSB per g, so that\n// the accelerometer biases calculated above must be divided by 8.\n\nint32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory\naccelerometer trim biases\nreadBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory\naccelerometer trim values\naccel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\nreadBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]);\naccel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\nreadBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]);\naccel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]);\n\nuint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of\nlower byte of accelerometer bias registers\nuint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each\naccelerometer bias axis\n\nfor(ii = 0; ii < 3; ii++) {\nif((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature\ncompensation bit is set, record that fact in mask_bit\n}\n\n// Construct total accelerometer bias, including calculated average\naccelerometer bias from above\naccel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged\naccelerometer bias scaled to 2048 LSB/g (16 g full scale)\naccel_bias_reg[1] -= (accel_bias[1]/8);\naccel_bias_reg[2] -= (accel_bias[2]/8);\n\ndata[0] = (accel_bias_reg[0] >> 8) & 0xFF;\ndata[1] = (accel_bias_reg[0]) & 0xFF;\ndata[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit\nwhen writing back to accelerometer bias registers\ndata[2] = (accel_bias_reg[1] >> 8) & 0xFF;\ndata[3] = (accel_bias_reg[1]) & 0xFF;\ndata[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit\nwhen writing back to accelerometer bias registers\ndata[4] = (accel_bias_reg[2] >> 8) & 0xFF;\ndata[5] = (accel_bias_reg[2]) & 0xFF;\ndata[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit\nwhen writing back to accelerometer bias registers\n\n// Apparently this is not working for the acceleration biases in the\nMPU-9250\n// Are we handling the temperature correction bit properly?\n// Push accelerometer biases to hardware registers\nwriteByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);\nwriteByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);\nwriteByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);\nwriteByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);\nwriteByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);\nwriteByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);\n\n// Output scaled accelerometer biases for display in the main program\ndest2[0] = (float)accel_bias[0]/(float)accelsensitivity; \ndest2[1] = (float)accel_bias[1]/(float)accelsensitivity;\ndest2[2] = (float)accel_bias[2]/(float)accelsensitivity;\n}\n\n// Accelerometer and gyroscope self test; check calibration wrt factory\nsettings\nvoid MPU9250SelfTest(float * destination) // Should return percent deviation\nfrom factory trim values, +/- 14 or less deviation is a pass\n{\nuint8_t rawData[6] = {0, 0, 0, 0, 0, 0};\nuint8_t selfTest[6];\nint16_t gAvg[3], aAvg[3], aSTAvg[3], gSTAvg[3];\nfloat factoryTrim[6];\nuint8_t FS = 0;\n\nwriteByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1\nkHz\nwriteByte(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz\nand DLPF to 92 Hz\nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, 1<<FS); // Set full scale range for\nthe gyro to 250 dps\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate\nto 1 kHz and bandwidth to 92 Hz\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, 1<<FS); // Set full scale range for\nthe accelerometer to 2 g\n\nfor( int ii = 0; ii < 200; ii++) { // get average current values of gyro and\nacclerometer\n\nreadBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six\nraw data registers into data array\naAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the\nMSB and LSB into a signed 16-bit value\naAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;\n\naAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \n\nreadBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);       // Read the\nsix raw data registers sequentially into data array\n\n\ngAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the\nMSB and LSB into a signed 16-bit value\ngAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;\n\ngAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \n}\n\nfor (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as\naverage current readings\naAvg[ii] /= 200;\ngAvg[ii] /= 200;\n}\n\n// Configure the accelerometer for self-test\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all\nthree axes and set accelerometer range to +/- 2 g\nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all\nthree axes and set gyro range to +/- 250 degrees/s\ndelay(25); // Delay a while to let the device stabilize\n\nfor( int ii = 0; ii < 200; ii++) { // get average self-test values of gyro\nand acclerometer\n\nreadBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six\nraw data registers into data array\naSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn\nthe MSB and LSB into a signed 16-bit value\naSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;\n\naSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \n\nreadBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]);  // Read the six\nraw data registers sequentially into data array\n\n\ngSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn\nthe MSB and LSB into a signed 16-bit value\ngSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;\n\ngSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ; \n}\n\nfor (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as\naverage self-test readings\naSTAvg[ii] /= 200;\ngSTAvg[ii] /= 200;\n} \n\n// Configure the gyro and accelerometer for normal operation\nwriteByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);\n\nwriteByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);\n\ndelay(25); // Delay a while to let the device stabilize\n\n// Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg\nselfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel\nself-test results\nselfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel\nself-test results\nselfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel\nself-test results\nselfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO); // X-axis gyro\nself-test results\nselfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO); // Y-axis gyro\nself-test results\nselfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO); // Z-axis gyro\nself-test results\n\n// Retrieve factory self-test value from self-test code reads\nfactoryTrim[0] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[0] - 1.0)\n)); // FT[Xa] factory trim calculation\nfactoryTrim[1] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[1] - 1.0)\n)); // FT[Ya] factory trim calculation\nfactoryTrim[2] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[2] - 1.0)\n)); // FT[Za] factory trim calculation\nfactoryTrim[3] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[3] - 1.0)\n)); // FT[Xg] factory trim calculation\nfactoryTrim[4] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[4] - 1.0)\n)); // FT[Yg] factory trim calculation\nfactoryTrim[5] = (float)(2620/1<<FS)(pow( 1.01 , ((float)selfTest[5] - 1.0)\n)); // FT[Zg] factory trim calculation\n\n// Report results as a ratio of (STR - FT)/FT; the change from Factory Trim\nof the Self-Test Response\n// To get percent, must multiply by 100\nfor (int i = 0; i < 3; i++) {\ndestination[i] = 100.0((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i]; //\nReport percent differences\ndestination[i+3] = 100.0((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3]; //\nReport percent differences\n}\n\n}\n\n    // Wire.h read and write protocols\n    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)\n\n\n{\nWire.beginTransmission(address); // Initialize the Tx buffer\nWire.write(subAddress); // Put slave register address in Tx buffer\nWire.write(data); // Put data in Tx buffer\nWire.endTransmission(); // Send the Tx buffer\n}\n\n    uint8_t readByte(uint8_t address, uint8_t subAddress)\n\n\n{\nuint8_t data; // data will store the register data\n\nWire.beginTransmission(address); // Initialize the Tx buffer\nWire.write(subAddress); // Put slave register address in Tx buffer\nWire.endTransmission(false); // Send the Tx buffer, but send a restart to\nkeep connection alive\nWire.requestFrom(address, (uint8_t) 1); // Read one byte from slave register\naddress \ndata = Wire.read(); // Fill Rx buffer with result\nreturn data; // Return data read from slave register\n}\n\n    void readBytes(uint8_t address, uint8_t subAddress, uint8_t count,\nuint8_t * dest)\n\n\n{\n\nWire.beginTransmission(address); // Initialize the Tx buffer\nWire.write(subAddress); // Put slave register address in Tx buffer\nWire.endTransmission(false); // Send the Tx buffer, but send a restart to\nkeep connection alive\nuint8_t i = 0;\nWire.requestFrom(address, count); // Read bytes from slave register address \nwhile (Wire.available()) {\ndest[i++] = Wire.read(); } // Put read results in the Rx buffer\n}\n\nvoid MadgwickQuaternionUpdate(float ax, float ay, float az, float gx, float\ngy, float gz, float mx, float my, float mz)\n{\nfloat q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local\nvariable for readability\nfloat norm;\nfloat hx, hy, _2bx, _2bz;\nfloat s1, s2, s3, s4;\nfloat qDot1, qDot2, qDot3, qDot4;\n\n// Auxiliary variables to avoid repeated arithmetic\nfloat _2q1mx;\nfloat _2q1my;\nfloat _2q1mz;\nfloat _2q2mx;\nfloat _4bx;\nfloat _4bz;\nfloat _2q1 = 2.0f * q1;\nfloat _2q2 = 2.0f * q2;\nfloat _2q3 = 2.0f * q3;\nfloat _2q4 = 2.0f * q4;\nfloat _2q1q3 = 2.0f * q1 * q3;\nfloat _2q3q4 = 2.0f * q3 * q4;\nfloat q1q1 = q1 * q1;\nfloat q1q2 = q1 * q2;\nfloat q1q3 = q1 * q3;\nfloat q1q4 = q1 * q4;\nfloat q2q2 = q2 * q2;\nfloat q2q3 = q2 * q3;\nfloat q2q4 = q2 * q4;\nfloat q3q3 = q3 * q3;\nfloat q3q4 = q3 * q4;\nfloat q4q4 = q4 * q4;\n\n// Normalise accelerometer measurement\nnorm = sqrt(ax * ax + ay * ay + az * az);\nif (norm == 0.0f) return; // handle NaN\nnorm = 1.0f/norm;\nax *= norm;\nay *= norm;\naz *= norm;\n\n// Normalise magnetometer measurement\nnorm = sqrt(mx * mx + my * my + mz * mz);\nif (norm == 0.0f) return; // handle NaN\nnorm = 1.0f/norm;\nmx *= norm;\nmy *= norm;\nmz *= norm;\n\n// Reference direction of Earth's magnetic field\n_2q1mx = 2.0f * q1 * mx;\n_2q1my = 2.0f * q1 * my;\n_2q1mz = 2.0f * q1 * mz;\n_2q2mx = 2.0f * q2 * mx;\nhx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 +\n_2q2 * mz * q4 - mx * q3q3 - mx * q4q4;\nhy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my *\nq3q3 + _2q3 * mz * q4 - my * q4q4;\n_2bx = sqrt(hx * hx + hy * hy);\n_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 +\n_2q3 * my * q4 - mz * q3q3 + mz * q4q4;\n_4bx = 2.0f * _2bx;\n_4bz = 2.0f * _2bz;\n\n// Gradient decent algorithm corrective step\ns1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 -\nay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx)\n+ (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) -\nmy) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);\ns2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay)\n- 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx *\n(0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1)\n* (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz *\nq2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);\ns3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 -\nay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 -\n_2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) +\n(_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my)\n+ (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 -\nq3q3) - mz);\ns4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay)\n+ (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 -\nq1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz *\n(q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f -\nq2q2 - q3q3) - mz);\nnorm = sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step\nmagnitude\nnorm = 1.0f/norm;\ns1 *= norm;\ns2 *= norm;\ns3 *= norm;\ns4 *= norm;\n\n// Compute rate of change of quaternion\nqDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;\nqDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;\nqDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;\nqDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;\n\n// Integrate to yield quaternion\nq1 += qDot1 * deltat;\nq2 += qDot2 * deltat;\nq3 += qDot3 * deltat;\nq4 += qDot4 * deltat;\nnorm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion\nnorm = 1.0f/norm;\nq[0] = q1 * norm;\nq[1] = q2 * norm;\nq[2] = q3 * norm;\nq[3] = q4 * norm;\n\n}\n\n// Similar to Madgwick scheme but uses proportional and integral filtering\non the error between estimated reference vectors and\n// measured ones.\nvoid MahonyQuaternionUpdate(float ax, float ay, float az, float gx, float\ngy, float gz, float mx, float my, float mz)\n{\nfloat q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local\nvariable for readability\nfloat norm;\nfloat hx, hy, bx, bz;\nfloat vx, vy, vz, wx, wy, wz;\nfloat ex, ey, ez;\nfloat pa, pb, pc;\n\n// Auxiliary variables to avoid repeated arithmetic\nfloat q1q1 = q1 * q1;\nfloat q1q2 = q1 * q2;\nfloat q1q3 = q1 * q3;\nfloat q1q4 = q1 * q4;\nfloat q2q2 = q2 * q2;\nfloat q2q3 = q2 * q3;\nfloat q2q4 = q2 * q4;\nfloat q3q3 = q3 * q3;\nfloat q3q4 = q3 * q4;\nfloat q4q4 = q4 * q4;\n\n// Normalise accelerometer measurement\nnorm = sqrt(ax * ax + ay * ay + az * az);\nif (norm == 0.0f) return; // handle NaN\nnorm = 1.0f / norm; // use reciprocal for division\nax *= norm;\nay *= norm;\naz *= norm;\n\n// Normalise magnetometer measurement\nnorm = sqrt(mx * mx + my * my + mz * mz);\nif (norm == 0.0f) return; // handle NaN\nnorm = 1.0f / norm; // use reciprocal for division\nmx *= norm;\nmy *= norm;\nmz *= norm;\n\n// Reference direction of Earth's magnetic field\nhx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f *\nmz * (q2q4 + q1q3);\nhy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f *\nmz * (q3q4 - q1q2);\nbx = sqrt((hx * hx) + (hy * hy));\nbz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz *\n(0.5f - q2q2 - q3q3);\n\n// Estimated direction of gravity and magnetic field\nvx = 2.0f * (q2q4 - q1q3);\nvy = 2.0f * (q1q2 + q3q4);\nvz = q1q1 - q2q2 - q3q3 + q4q4;\nwx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);\nwy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);\nwz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);\n\n// Error is cross product between estimated direction and measured direction\nof gravity\nex = (ay * vz - az * vy) + (my * wz - mz * wy);\ney = (az * vx - ax * vz) + (mz * wx - mx * wz);\nez = (ax * vy - ay * vx) + (mx * wy - my * wx);\nif (Ki > 0.0f)\n{\neInt[0] += ex; // accumulate integral error\neInt[1] += ey;\neInt[2] += ez;\n}\nelse\n{\neInt[0] = 0.0f; // prevent integral wind up\neInt[1] = 0.0f;\neInt[2] = 0.0f;\n}\n\n// Apply feedback terms\ngx = gx + Kp * ex + Ki * eInt[0];\ngy = gy + Kp * ey + Ki * eInt[1];\ngz = gz + Kp * ez + Ki * eInt[2];\n\n// Integrate rate of change of quaternion\npa = q2;\npb = q3;\npc = q4;\nq1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);\nq2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);\nq3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);\nq4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);\n\n// Normalise quaternion\nnorm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);\nnorm = 1.0f / norm;\nq[0] = q1 * norm;\nq[1] = q2 * norm;\nq[2] = q3 * norm;\nq[3] = q4 * norm;\n\n}\n\n-\nReply to this email directly or view it on GitHub\n<https://github.com/kriswiner/MPU-9250/issues/22> .\n<https://github.com/notifications/beacon/AGY1qkycsTVTPDMgronauj-QnwWVqs4Cks5\no1YqHgaJpZM4GEBah.gif> \n\n\n"}}