Can't get MPU6050 and Jeff Rowberg's DMP code to work.

I’m trying to get my balanced robot to work. I’m using part of Jeff Rowberg’s DMP code to sense the pitch with a MPU6050 board. It freezes up after a time and there is no more output on the serial monitor. The unmodified code runs fine.
I’m using an Arduino UNO.
I need 9600 baud rate or I get garbage.
FIFO overflow happens now and again but not consistently.
I’m using two continuous servos and will switch to gearmoters if I can get sketch to work properly.
If I knew exactly how the code works I could probably fix it but I’m at about 30% understanding. I’d be willing to use the raw output with a complimentay filter if I understood how to do it. I’ve done alot of reading but I would have to say that good programmers are not good communicators. I have a hard time comprehending the code without comments on what it does and why it’s used. Comments on how my version works are what I copied. Anyway, help on how to stop the code from freezing would be greatly appreciated. Thanks.

The code:

[
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include <Servo.h> 
#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

#define OUTPUT_READABLE_YAWPITCHROLL

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector




// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}



// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================
Servo myservoR;
Servo myservoL;
void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(9600);

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}



// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    myservoL.attach(9);
    myservoR.attach(11);
  
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        
        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;



     OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  
           
     int routVal = (ypr[2] * 180/M_PI) + 90; //Get right servo value.
     int loutVal = 180 - routVal; //Get left servo value.
     int loffSet = loutVal - 6;
     int roffSet = routVal + 3;
     Serial.println(loffSet);
     Serial.print(roffSet);

     myservoL.write(loffSet);
     myservoR.write(roffSet);
        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}/code]

Can you post the original code that works so we can compare them?

Yeah, I had a look at the code and ended up on the “Quaternion” wikipedia page. I closed that soon after. Anyway, it shows that it is often harder to understand someone elses program then it is to write a new one.

However, I can post something useful, a complimentary filter is very simple, it goes like this:

angle = 0.90 * ( gyro + angle) + 0.10 * acceleration_derived_angle;

This works because last part acts as a low pass filter and the first part as a (pseudo) high pass filter. A better explanation can be found at http://web.mit.edu/scolton/www/filter.pdf.

The unmodified code runs fine.

Can you post the unmodified code, please?

The full code is too large to post. You can view it here:

https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino

Thanks Silver. I've got some questions. I'm confused as usual.

angle = 0.90 * ( gyro + angle) + 0.10 * acceleration_derived_angle;

What values are used for (gyro+angle) and acceleration_derived_angle? All I have are raw numbers from the gyro /accel chip.
Thanks again to both for your help.

Pierre

Nick, here is what I did to modify the code besides deleting the parts I didn't think I needed.

[  OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  
           
     int routVal = (ypr[2] * 180/M_PI) + 90; //Get right servo value.
     int loutVal = 180 - routVal; //Get left servo value.
     int loffSet = loutVal - 6;
     int roffSet = routVal + 3;
     Serial.println(loffSet);
     Serial.print(roffSet);

     myservoL.write(loffSet);
     myservoR.write(roffSet);/code]

Thanks,

Pierre

More Info:

The sketch runs continuously if I don't power the servos. They have a separate power supply and the grounds are common. So I think I may have some RF or interupt problems or both.

Little did I realize the mountain of confusing information I would have to deal with when I decided to do this project. This is a hobby and supposed to be fun. It's turning out to be only frustrating. I think I'll forget balancing and do a hexapod which is what I thought of first. That I can understand. The balanced bot is cheaper but not fun.

Thanks again.

Pierre

This latest information suggests you indeed have power problems. It is certainly not unusual for spikes to introduce resets or cause other problems.