Arduino PID problems

This forum is dedicated to software development related to MultiWii.
It is not the right place to submit a setup problem.
Software download
Post Reply
geekyd00d
Posts: 1
Joined: Sun Nov 16, 2014 10:20 pm

Arduino PID problems

Post by geekyd00d »

Hi guys, I'm making a small (250mm) quadcopter and I'm having trouble getting it to balance. I'm using the x configuration, and I have it set up in a string test rig to test one axis (pitch / roll) at a time. I'm using an arduino uno as my flight controller. I spent a while searching for source code that just balanced the quadcopter and found this page : http://www.instructables.com/id/3D-P.../step6/Coding/ I then edited the code to suit my set up. This is my altered version of that code :

Code: Select all

#include "I2Cdev.h"
#include <PID_v1.h>
#include <Servo.h>
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;

Servo prop1;
Servo prop2;
Servo prop3;
Servo prop4;

 #define OUTPUT_READABLE_YAWPITCHROLL



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



// ================================================================
// ===               Stablization set up stuff               ===
// ================================================================

double pdif, rdif;
double setpitch, setroll;
double pitch, roll;



// DEFINED STUFF HERE
//desired stable rotor speed
//don't keep near 255, because then hard for the copter to control the craft. It needs the room
//to vary the speed of different rotors
#define UP 29
int spd = UP;

PID pitchPID(&pitch, &pdif, &setpitch, 100, 2, 30, DIRECT); //the numbers are p, i , and d
PID rollPID(&roll, &rdif, &setroll, 100,  2, 30, DIRECT);


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

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



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

void setup() {
 
    prop1.attach(3); //
    prop2.attach(4); // front
    prop3.attach(5); //
    prop4.attach(6); // back
   
    prop1.write(10);
    prop2.write(10);
    prop3.write(10);
    prop4.write(10);
   
    // 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

    Serial.begin(115200);

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

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

    // GYRO OFFSETS
    mpu.setXGyroOffset(66);
    mpu.setYGyroOffset(-43);
    mpu.setZGyroOffset(59);   
    mpu.setXAccelOffset(-3418);
    mpu.setYAccelOffset(1026);
    mpu.setZAccelOffset(1490);

    // 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 stabilization code
    //=============================
    pdif = 0.0;
    rdif = 0.0;
    setpitch = 0.0;
    setroll = 0.0;
    pitch = 0.0;
    roll = 0.0;
   
    pitchPID.SetMode(AUTOMATIC);
    rollPID.SetMode(AUTOMATIC);   
   
    pitchPID.SetOutputLimits(-20, 20);
    rollPID.SetOutputLimits(-20, 20);
}



// ================================================================
// ===                    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*/) {
          int p1 = spd /* + (rdif / 2)*/ - (pdif / 2);
          int p2 = spd /* + (rdif / 2)*/ + (pdif / 2);
          int p3 = spd /* - (rdif / 2)*/ - (pdif / 2);
          int p4 = spd /* - (rdif / 2)*/ + (pdif / 2);
         
          if(p1 >= 40){
            //reduce speed so can stabilise
            spd -= (p1 - 40);
           continue;
          }
          if(p2 >= 40){
            spd -= (p2 - 40);
          continue;
          }
          if(p3 >= 40){
            spd -= (p3 - 40);
           continue;
          }
          if(p4 >= 40){
            spd -= (p4 - 40);
           continue;
          }
       
        prop1.write(p1);
         prop2.write(p2);
         prop3.write(p3);
         prop4.write(p4);
         

    }

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

       
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        pitch = (ypr[1] * 180/M_PI);
        roll = (ypr[2] * 180/M_PI);
       
        pitch = pitch * -1;
        roll = roll * -1;
   
        //Update Pids
        pitchPID.Compute();
        rollPID.Compute();
       
         //Increase spd if we've reduced spd
        if(spd < UP){
            spd++;
        }
    }
}


My problem is that the quad can't balance. It looks like it's over-correcting and then oscillating.So far, changing the p, i and d coefficients doesn't seem to do a whole lot. The quad just keeps bouncing back and forth, see-sawing but not leveling. The code is set up so that it only tries to balance on one axis. The pid values are the best ones I've found. Can anyone give me advice on how to change to the right pid values or how to know which ones to change? Is this code even right? I've tried reading through the multiwii source but I can't understand it. Any help at all would be appreciated. Thanks.

Any help would be greatly appreciated. Thanks.

waltr
Posts: 733
Joined: Wed Jan 22, 2014 3:21 pm
Location: Near Philadelphia, Pennsyvania, USA

Re: Arduino PID problems

Post by waltr »

Scrap that code and load MultiWii2.3 code into the Arduino.

Post Reply