I'm having some problem with the MPU6050 example sketch. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:

ypr -38.68  -30.05  41.34
ypr -55.42  -35.25  -31.68
ypr -101.02 23.53   -65.01
ypr 101.29  -19.63  12.81
ypr -51.97  -37.49  44.85
ypr 37.89   38.20   -37.95
ypr 72.15   -13.70  22.68
ypr 0.00    0.00    90.00
ypr -45.73  74.52   -11.89
ypr 134.36  31.89   -31.08
ypr -13.86  -21.51  3.54

And when I disable analogWrite on the LED lights the yaw-pitch-roll gives normal output again.

Below is the code for changing the LED colors.

void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);

Does anyone know what is going wrong here?


The wiring:

Wiring of my project

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 "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
    #include "Wire.h"

// 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

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo

#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

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

int redPin = 11;
int bluePin = 9;

int startR = 100;
int startB = 10;

int eindR = 255;
int eindB = 255;

int gyroMin = 0;
int gyroMax = 80;
int gyroRange = 0;
float rangeR = 0;
float rangeB = 0;

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

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

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        Fastwire::setup(400, true);

    gyroRange = (gyroMax - 10) - (gyroMin + 10);
    rangeR = (float)(eindR - startR)/gyroRange;
    rangeB = (float)(eindB - startB)/gyroRange;

    while (!Serial);

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

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

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    /*while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again*/

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

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setZAccelOffset(1); // 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..."));

        // 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 "));

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
    pinMode(redPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    //digitalWrite(redPin, LOW);
    //digitalWrite(bluePin, LOW);

void loop() {
    // 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

    // 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
        Serial.println(F("FIFO overflow!"));
        } else if (mpuIntStatus & 0x02) {
          // otherwise, check for DMP data ready interrupt (this should happen frequently)
         // 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;

            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);

            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print(euler[0] * 180/M_PI);
            Serial.print(euler[1] * 180/M_PI);
            Serial.println(euler[2] * 180/M_PI);

            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print(ypr[1] * 180/M_PI);
            Serial.println(ypr[2] * 180/M_PI);
            int degree = ypr[1] * 180/M_PI;
            if (degree <= (gyroMin + 10)){
              setColor(startR, startB);
            if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
              float calcR = (startR + ((degree-10) * rangeR));
              float calcB = (startB + ((degree-10) * rangeB));
            if (degree >= (gyroMax - 10)){
              setColor(eindR, eindB);

            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);

            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);

EDIT 2: After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.

Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

  • Not without seeing both the entirety of your code and the wiring of your circuit.
    – Majenko
    May 6, 2017 at 18:43
  • @Majenko thanks for the quick reply, i uploaded a screenshot of the wiring and added the full code May 6, 2017 at 19:03
  • Just a question. Why you pass float variable as colour? Try int. analogWrite change the value to 8bit.
    – Martynas
    May 6, 2017 at 19:14
  • Jimi just quick test. Take off LEDs and try the code if there is any difference. Also try to pass integer instead of float
    – Martynas
    May 7, 2017 at 17:46
  • Yeah did that, then the output is stable. May 7, 2017 at 19:22

1 Answer 1


You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.

Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).

  • but the led are in series, do I still need 9 resistors or just 3? May 6, 2017 at 19:22
  • 1
    No, they aren't in series. They are in parallel. Every single LED needs a resistor, and there's 3 resistors per device, and 3 devices, so 9 resistors.
    – Majenko
    May 6, 2017 at 19:23
  • Aah right, my bad. I will try to add the resistor and will let you know if it works. thanks for all the help so far! :D May 6, 2017 at 19:26
  • I added the resistors, but it still isn't working + now the leds are very dim (which is not what I want), what now? May 6, 2017 at 20:08
  • 1
    The MPU board you have pictured looks like it should be powered by 5V not 3.3V.
    – Majenko
    May 6, 2017 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.