user81423: So, I have a working code of the stabilizer project using 2 servo motors, mpu6050, Arduino Uno. However, I want to add PID part for tuning the servo motors movement. I followed the example PID library and just changed the input as data received from the mpu6050 sensor, and output as the data that we send to servo motor. The problem is after adding the PID part project stopped working properly. Servo motors did not react to the accelerometer movement anymore. I tried printing out the values computed by the PID and all of them turned out to be 0 and they don't change even if I rotate the sensor. Can anyone spot the mistake in the code with PID part? I am pretty sure that the rest works perfectly.
/*
                        DIY Gimbal - MPU6050 Arduino Tutorial
                        by Dejan, www.HowToMechatronics.com
                        Code based on the MPU6050_DMP6 example from the i2cdevlib library by Jeff Rowberg:
                        https://github.com/jrowberg/i2cdevlib
*/
// 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
#include "PID_v1.h"

// 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
#include <Servo.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

double Setpointx, Setpointy, Inputx, Inputy, Outputx, Outputy, pidX, pidY;
double Kp = 2, Ki = 5, Kd = 1;
PID myPID0 (&Inputx, &Outputx, &Setpointx, Kp, Ki, Kd, DIRECT) ;
PID myPID1 (&Inputy, &Outputy, &Setpointy, Kp, Ki, Kd, DIRECT) ;
// Define the 3 servo motors
Servo servo0;
Servo servo1;
Servo servo2;
float correct;
int j = 0;

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

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' };



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

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

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Setpointx = 10;
  Setpointy = 10;

  myPID0. SetMode (AUTOMATIC);
  myPID1. SetMode (AUTOMATIC);

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#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(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  //Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(17);
  mpu.setYGyroOffset(-69);
  mpu.setZGyroOffset(27);
  mpu.setZAccelOffset(1551); // 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);

    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), 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(")"));
  }

  // Define the pins to which the 3 servo motors are connected
  servo0.attach(10); //Z Axis
  servo1.attach(9); //Y Axis
  servo2.attach(8); //X Axis
  servo1.write(90);
  servo2.write(90);
}
// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

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) {
    if (mpuInterrupt && fifoCount < packetSize) {
      // try to get out of the infinite loop
      fifoCount = mpu.getFIFOCount();
    }
  }

  // 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 & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    fifoCount = mpu.getFIFOCount();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
    // 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;

    // Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    // Yaw, Pitch, Roll values - Radians to degrees
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    Serial.print("\nX: ");
    Serial.print(pidX);
    Serial.print("\nY: ");
    Serial.print(pidY);
    ypr[0] = ypr[0] * 180 / M_PI;
    pidX = pidX * 180 / M_PI;
    pidY = pidY * 180 / M_PI;
    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(pidY, -90, 90, 0, 180);
      int servo2Value = map(pidX, -90, 90, 180, 0);
      // Control the servos according to the MPU6050 orientation
      servo0.write(90);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif
  }
}


user42015: You seem to have some misconceptions about PID. For explaining I will use a different use case of a PID control, which is easier to understand (and also mentioned in the documentation of the PID library):
A PID control can be used in any feedback loop system with consistent feedback. When you drive your car you want it to reach a specific speed. For that you press the gas pedal, changing its angle until you reach the target speed. In this scenario you are doing the PID control. The setpoint is the target speed, the input is the actual current speed and the output is the angle of the gas pedal.
You see: Output and input/setpoint don't have the same unit. They are completely different measurements of different things. They are only connected via the feedback loop in the system, meaning that increasing the gas pedal angle will increase the speed of the car. The PID control is then just a formula which involves the actual speed, the desired speed and some scaling variables (Kp, Ki, Kd)(to tune the behavior of the control). And the output of the formula is then the needed gas pedal angle at that time.
So what does this mean for you?

You don't need to convert the output value into an angle. The unit of the output is not important, since the PID will control itself to get to the setpoint. It is more important to tune the PID through Kp, Ki and Kd to get the PID to behave correctly in your system.

The workflow looks like this:

Set the setpoint variable Setpointx to the wanted input value.
Read the input from the MPU and save it to Inputx
Call myPID0.Compute(); to compute the output from setpoint and input.
Read the value from Outputx and write it to your servo. The servo movement will then cause a change in the read input in the next loop.
repeat from step 2


As I currently don't really understand your feedback loop system: Make sure, that the feedback loop is working correctly. An increase in the output should lead to an increase in the input. Make sure it is consistent. Your input value should not have too much noise (or the PID will react to that noise). For testing you might want to tune Kp, Ki and Kd down so that the PID works slower. Then you can see the behavior better. Make sure, that both PID controls aren't influencing each other. They need to be independent.

Use myPID0.Compute(); every time you write a new value to your servo and only then. Calling it in between will be just a waste. So it makes sense to use that line somewhere directly before writing to the servo.



If it still not works, then you should have a detailed look at the read values and how they relate to the servo angle. Are the requirements above met? Are they stable enough. Is the feedback loop as expected? What does changing Kp, Kd and Ki change in the outcome?

81423: <p>So, I have a working code of the stabilizer project using 2 servo motors, mpu6050, Arduino Uno. However, I want to add PID part for tuning the servo motors movement. I followed the example PID library and just changed the input as data received from the mpu6050 sensor, and output as the data that we send to servo motor. The problem is after adding the PID part project stopped working properly. Servo motors did not react to the accelerometer movement anymore. I tried printing out the values computed by the PID and all of them turned out to be 0 and they don't change even if I rotate the sensor. Can anyone spot the mistake in the code with PID part? I am pretty sure that the rest works perfectly.</p>
<pre class="lang-cpp prettyprint-override"><code>/*
                        DIY Gimbal - MPU6050 Arduino Tutorial
                        by Dejan, www.HowToMechatronics.com
                        Code based on the MPU6050_DMP6 example from the i2cdevlib library by Jeff Rowberg:
                        https://github.com/jrowberg/i2cdevlib
*/
// 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 &quot;I2Cdev.h&quot;

#include &quot;MPU6050_6Axis_MotionApps20.h&quot;
//#include &quot;MPU6050.h&quot; // not necessary if using MotionApps include file
#include &quot;PID_v1.h&quot;

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include &quot;Wire.h&quot;
#endif
#include &lt;Servo.h&gt;
// 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); // &lt;-- use for AD0 high

double Setpointx, Setpointy, Inputx, Inputy, Outputx, Outputy, pidX, pidY;
double Kp = 2, Ki = 5, Kd = 1;
PID myPID0 (&amp;Inputx, &amp;Outputx, &amp;Setpointx, Kp, Ki, Kd, DIRECT) ;
PID myPID1 (&amp;Inputy, &amp;Outputy, &amp;Setpointy, Kp, Ki, Kd, DIRECT) ;
// Define the 3 servo motors
Servo servo0;
Servo servo1;
Servo servo2;
float correct;
int j = 0;

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno &amp; most boards

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' };



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

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

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Setpointx = 10;
  Setpointy = 10;

  myPID0. SetMode (AUTOMATIC);
  myPID1. SetMode (AUTOMATIC);

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#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(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  //Serial.println(F(&quot;Initializing I2C devices...&quot;));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(17);
  mpu.setYGyroOffset(-69);
  mpu.setZGyroOffset(27);
  mpu.setZAccelOffset(1551); // 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(&quot;Enabling DMP...&quot;));
    mpu.setDMPEnabled(true);

    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), 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(&quot;DMP ready! Waiting for first interrupt...&quot;));
    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(&quot;DMP Initialization failed (code &quot;));
    //Serial.print(devStatus);
    //Serial.println(F(&quot;)&quot;));
  }

  // Define the pins to which the 3 servo motors are connected
  servo0.attach(10); //Z Axis
  servo1.attach(9); //Y Axis
  servo2.attach(8); //X Axis
  servo1.write(90);
  servo2.write(90);
}
// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

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 &amp;&amp; fifoCount &lt; packetSize) {
    if (mpuInterrupt &amp;&amp; fifoCount &lt; packetSize) {
      // try to get out of the infinite loop
      fifoCount = mpu.getFIFOCount();
    }
  }

  // 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 &amp; _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount &gt;= 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    fifoCount = mpu.getFIFOCount();
    Serial.println(F(&quot;FIFO overflow!&quot;));

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

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is &gt; 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    // Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&amp;q, fifoBuffer);
    mpu.dmpGetGravity(&amp;gravity, &amp;q);
    mpu.dmpGetYawPitchRoll(ypr, &amp;q, &amp;gravity);

    // Yaw, Pitch, Roll values - Radians to degrees
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    Serial.print(&quot;\nX: &quot;);
    Serial.print(pidX);
    Serial.print(&quot;\nY: &quot;);
    Serial.print(pidY);
    ypr[0] = ypr[0] * 180 / M_PI;
    pidX = pidX * 180 / M_PI;
    pidY = pidY * 180 / M_PI;
    // Skip 300 readings (self-calibration process)
    if (j &lt;= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(pidY, -90, 90, 0, 180);
      int servo2Value = map(pidX, -90, 90, 180, 0);
      // Control the servos according to the MPU6050 orientation
      servo0.write(90);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif
  }
}
</code></pre>
 42015: <p>You seem to have some misconceptions about PID. For explaining I will use a different use case of a PID control, which is easier to understand (and also mentioned in the <a href="https://playground.arduino.cc/Code/PIDLibrary/" rel="nofollow noreferrer">documentation of the PID library</a>):</p>
<p>A PID control can be used in any feedback loop system with consistent feedback. When you drive your car you want it to reach a specific speed. For that you press the gas pedal, changing its angle until you reach the target speed. In this scenario you are doing the PID control. The setpoint is the target speed, the input is the actual current speed and the output is the angle of the gas pedal.</p>
<p>You see: Output and input/setpoint don't have the same unit. They are completely different measurements of different things. They are only connected via the feedback loop in the system, meaning that increasing the gas pedal angle will increase the speed of the car. The PID control is then just a formula which involves the actual speed, the desired speed and some scaling variables (Kp, Ki, Kd)(to tune the behavior of the control). And the output of the formula is then the needed gas pedal angle at that time.</p>
<p><strong>So what does this mean for you?</strong></p>
<ul>
<li><p>You don't need to convert the output value into an angle. The unit of the output is not important, since the PID will control itself to get to the setpoint. It is more important to tune the PID through Kp, Ki and Kd to get the PID to behave correctly in your system.</p>
</li>
<li><p>The workflow looks like this:</p>
<ol>
<li>Set the setpoint variable <code>Setpointx</code> to the wanted input value.</li>
<li>Read the input from the MPU and save it to <code>Inputx</code></li>
<li>Call <code>myPID0.Compute();</code> to compute the output from setpoint and input.</li>
<li>Read the value from <code>Outputx</code> and write it to your servo. The servo movement will then cause a change in the read input in the next loop.</li>
<li>repeat from step 2</li>
</ol>
</li>
<li><p>As I currently don't really understand your feedback loop system: Make sure, that the feedback loop is working correctly. An increase in the output should lead to an increase in the input. Make sure it is consistent. Your input value should not have too much noise (or the PID will react to that noise). For testing you might want to tune Kp, Ki and Kd down so that the PID works slower. Then you can see the behavior better. Make sure, that both PID controls aren't influencing each other. They need to be independent.</p>
</li>
<li><p>Use <code>myPID0.Compute();</code> every time you write a new value to your servo and only then. Calling it in between will be just a waste. So it makes sense to use that line somewhere directly before writing to the servo.</p>
</li>
</ul>
<hr />
<p>If it still not works, then you should have a detailed look at the read values and how they relate to the servo angle. Are the requirements above met? Are they stable enough. Is the feedback loop as expected? What does changing Kp, Kd and Ki change in the outcome?</p>
