0

I am currently working on a quadcopter project that involves an MPU6050 accelerometer+gyroscope module, an ultrasonic sensor and control of electronic speed controllers. I have used existing examples and modified them to get raw values of acceleration, yaw pitch and roll angles, and the distance from the ultrasonic. Here is the long code.

#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file


#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

const int trigPin = 9;
const int echoPin = 10;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#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;
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], yprd[3] = {0, 0, 0};

// 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;
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================
int16_t yo = 0, po = 0, ro = 0;
int lv = 1, flag = 0;
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int32_t AcXo = 0, AcYo = 0, AcZo = 0, prev, curr;
int32_t AcXd = 0, AcYd = 0, AcZd = 0;
int i = 1, flaggl = 0;
int  glc = 0, lv2 = 1;
long duration;
int distance, distanced;
void setup() {

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(115200);
  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  // 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.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(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(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
  glc = 0;
  distance = distanced = 0;
}

// ================================================================
// ===                    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) {
  }
  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;
    //#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    if (millis() > 30000 && flag == 0) {
      if ( flag == 0 && lv  < 21) {
        yo += ypr[0] * 180 / M_PI;
        po += ypr[1] * 180 / M_PI;
        ro += ypr[2] * 180 / M_PI;
        ++lv;
      } else if (flag == 0) {
        flag = 1;
        yo /= 20;
        po /= 20;
        ro /= 20;
      }
    }
    //#endif
    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    mpu.resetFIFO();
    if (i < 21 && !flaggl) {
      AcXo += AcX;
      AcYo += AcY;
      AcZo += AcZ;
      ++i;
      Serial.println();
      Serial.println("***************************************************************************");
    } else if (!flaggl) {
      flaggl = 1;
      AcXo  = AcXo / 20;
      AcYo = AcYo / 20;
      AcZo = AcZo / 20;
    }
    curr = (AcZ - AcZo / 100);
    if (prev == curr )
      ++glc;
    else {
      glc = 0;
      prev = curr;
    }
    if (glc == 10) {
      Serial.println("lock broken!!!");
      glc = 0;
      loop();
    }
    if (flag == 1 && flaggl == 1) {
      if (lv2 < 21) {
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        distance = duration * 0.034 / 2;
        AcXd += (AcX - AcXo) / 100;
        AcYd += (AcY - AcYo) / 100;
        AcZd += (AcZ - AcZo) / 100;
        yprd[0] += ypr[0] * 180 / M_PI - yo;
        yprd[1] += ypr[1] * 180 / M_PI - po;
        yprd[2] += ypr[2] * 180 / M_PI - ro;
        distanced += distance;
        ++lv2;
      } else {
        AcXd /= 20;
        AcYd /= 20;
        AcZd /= 20;
        yprd[0] /= 20;
        yprd[1] /= 20;
        yprd[2] /= 20;
        distanced /= 20;
        lv2 = 1;
        Serial.print("AcX = ");
        Serial.print(AcXd);
        Serial.print(" | AcY = ");
        Serial.print(AcYd);
        Serial.print(" | AcZ = ");
        Serial.print(AcZd);
        Serial.print(" | yaw = ");
        Serial.print(yprd[0]);
        Serial.print(" | pitch = ");
        Serial.print(yprd[1]);
        Serial.print(" | roll = ");
        Serial.print(yprd[2]);
        Serial.print(" | distance = ");
        Serial.println(distanced);
        AcXd  = 0;
        AcYd = 0;
        AcZd = 0;
        yprd[0] = 0;
        yprd[1] = 0;
        yprd[2] = 0;
        distanced = 0;
      }
    }
  }
}

The code involves offset calculation and displays the averaged instantaneous values. After overcoming the problems of FIFO buffer overflow and some other typical issues, I've managed to get the code running but the the Arduino hangs after sometime (code tested on both Uno and Nano).

Therefore, it seems that maybe I need a higher clock speed. So, I had a look through other Arduino boards and Due seemed to be the solution, as it has a clock speed of 84MHz, compared to Uno's 16 MHz. Therefore, my question is that will the libraries and functions used in this code be compatible with the Due? Also, can the 3.3V operation of the Due, compared to Uno's 5V, present any problem in interfacing it with other sensors mentioned?

  • You should probably spend some time looking at existing post-ATmega open source aircraft designs. The chip from a DUE can probably be made to a work; a lot of incumbent designs use comparable STM32, GigaDevices, and Nuvoton ARM Cortex MCUs... and also some other MCUs and especially MCU/radio chips basically undocumented in the west. – Chris Stratton Mar 23 '18 at 18:36
  • Arduino Due is a dead product, and has been from its birth. It is too powerful to be used just for flashing LEd's.Yes, you can make it work for your project but caveat emptor - do not expect much sympathy from Arduino. – Jan Hus Aug 21 '18 at 21:31
0

Therefore, my question is that will be the libraries and functions used in this code be compatiable with Due?

The I2Cdev library is made for abstracting the hardware I2C functions to a more user friendly interface for each chip. Since the Arduino Due has hardware TWI (which is basically I2C) the normal Wire library from the Arduino IDE should work with it.

Also, can the 3.3V operation of Due, compared to Uno's 5V present any problem in interfacing it with other sensors mentioned?

You cannot put 5V from your sensor on a 3.3V pin on the Arduino Due, since this would destroy the pins hardware. I don't know how exactly you are using the MPU6050, but this one from Adafruit runs on 3.3V, which would be perfect. If your MPU6050 board only works with 5V maybe you can level shift the lines (but note that I2C would need 2-way level shifting, because SDA is used as output and input).

Also this Article may help you, where they are porting MultiWii to an Arduino Due.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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