Problem using NRF24 and MPU6050 with DMP enabled

Hi!

I have a NRF24 and a NRF24 with an antenna but they dont catch each other. The code I have is for my drone but I have taken out the code for just the radio so its easier to see whats happening. Here it is:

Reciver:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 radio(9, 10);
byte addresses[][6] = {"00001", "00002"};

void setup() {
  Serial.begin(115200);
  while (!Serial);

  radio.begin();

  radio.openReadingPipe(1, addresses[1]);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char read_input_throttle[32] = "";
    radio.read(&read_input_throttle, sizeof(read_input_throttle));
    input_throttle = atof(read_input_throttle);
    Serial.println(input_throttle);
} else {
    Serial.println("Radio not avalible");
    delay(500);

  }

Transmitter:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

// Create Radio and define pins
RF24 radio(8, 9);

// Create Radio channels
byte addresses[][6] = {"00001", "00002"};

void setup() {
  Serial.begin(9600);

  // Start radio communication
  radio.begin();
  radio.openWritingPipe(addresses[1]); // 00002
  radio.setPALevel(RF24_PA_MIN);
}

void loop() {
  delay(100);
  radio.stopListening();
  
  int input_throttle = map(analogRead(A0), 0, 1023, 1000, 1500);
  radio.write(&input_throttle, sizeof(input_throttle));

  Serial.println(input_throttle);
}

If you want the entire code for the flight controller just tell me :slight_smile:, Thanks beforehand!

  • Update *
    I can now send values from my transmitter to my reciver but my MPU6050 gyro does not output real values, it outputs the values 0 0 0 (ypr). When I test it with the same wiring but with the I2Cdev MPU6050 library it works perfectly. I cannot figure out why the values are 0. Here is my code for the flight controller:
#include <ESC.h>
#include "I2Cdev.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include "MPU6050_6Axis_MotionApps20.h"

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

MPU6050 mpu;

#define OUTPUT_READABLE_YAWPITCHROLL

ESC motor_LF;
ESC motor_RF;
ESC motor_LB;
ESC motor_RB;

RF24 radio(8, 9);
byte addresses[][6] = {"00001", "00002"};

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13
bool blinkState = false;

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

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

uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

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

int read_input_throttle;
float input_throttle;

/* Valut */
float elapsedTime, time, timePrev;
long loop_timer;

/* Roll PID */
float roll_PID, pid_throttle_L_F, pid_throttle_L_B, pid_throttle_R_F, pid_throttle_R_B, roll_error, roll_previous_error;
float roll_pid_p = 0;
float roll_pid_i = 0;
float roll_pid_d = 0;
/* Roll PID Constants */
double roll_kp = 7;
double roll_ki = 0.006;
double roll_kd = 1.2;
float roll_desired_angle = 0;

/* Pitch PID */
float pitch_PID, pitch_error, pitch_previous_error;
float pitch_pid_p = 0;
float pitch_pid_i = 0;
float pitch_pid_d = 0;
/* Pitch PID Constants */
double pitch_kp = 72;
double pitch_ki = 0.006;
double pitch_kd = 1.22;
float pitch_desired_angle = 0;

/* Accelerometer X PID */
float accX_PID, accX_error, accX_previous_error;
float accX_pid_p = 0;
float accX_pid_i = 0;
float accX_pid_d = 0;
/* Accelerometer X PID Constants */
double accX_kp = 72;
double accX_ki = 0.006;
double accX_kd = 1.22;

/* Accelerometer Y PID */
float accY_PID, accY_error, accY_previous_error;
float accY_pid_p = 0;
float accY_pid_i = 0;
float accY_pid_d = 0;
/* Accelerometer Y PID Constants */
double accY_kp = 72;
double accY_ki = 0.006;
double accY_kd = 1.22;

void setup() {


  // join I2C bus (I2Cdev library doesn't do this automatically)
#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

  Serial.begin(115200);
  while (!Serial);

  radio.begin();

  radio.openReadingPipe(1, addresses[1]);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();

  motor_LF.attach(4);
  motor_RF.attach(5);
  motor_LB.attach(6);
  motor_RB.attach(7);

  motor_LF.writeMicroseconds(1000);
  motor_RF.writeMicroseconds(1000);
  motor_LB.writeMicroseconds(1000);
  motor_RB.writeMicroseconds(1000);

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

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

  if (devStatus == 0) {
    // Calibration Time: generate offsets and calibrate our MPU6050
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    mpu.PrintActiveOffsets();
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
    Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
    Serial.println(F(")..."));
    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!"));
    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(")"));
  }

  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  if (radio.available()) {
    // if setup fail dont run the program
    if (!dmpReady) return;

    radio.read(&read_input_throttle, sizeof(read_input_throttle));
    input_throttle = read_input_throttle;

    /* Start Timer */
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;
    
    /* PID */
    roll_error = roll_desired_angle - (ypr[2] * 180 / M_PI);
    pitch_error = pitch_desired_angle - (ypr[1] * 180 / M_PI);

    /* Acceleromteter PID */
    accX_error = 0 - aaReal.x;
    accY_error = 0 - aaReal.y;

    /* Prospect */
    roll_pid_p = roll_kp * roll_error;
    pitch_pid_p = pitch_kp * pitch_error;

    /* Acceleromteter Prospect */
    accX_pid_p = accX_kp * accX_error;
    accY_pid_p = accY_kp * accY_error;

    /* Integral */
    if (-3 < roll_error < 3)
    {
      roll_pid_i = roll_pid_i + (roll_ki * roll_error);
    }
    if (-3 < pitch_error < 3)
    {
      pitch_pid_i = pitch_pid_i + (pitch_ki * pitch_error);
    }

    /* Acceleromteter Integral */
    if (-3 < accX_error < 3)
    {
      accX_pid_i = accX_pid_i + (accX_ki * accX_error);
    }
    if (-3 < accY_error < 3)
    {
      accY_pid_i = accY_pid_i + (accY_ki * accY_error);
    }


    /* Derivate */
    roll_pid_d = roll_kd * ((roll_error - roll_previous_error) / elapsedTime);
    pitch_pid_d = pitch_kd * ((pitch_error - pitch_previous_error) / elapsedTime);


    /* Acceleromteter Derivate */
    accX_pid_d = accX_kd * ((accX_error - accX_previous_error) / elapsedTime);
    accY_pid_d = accY_kd * ((accY_error - accY_previous_error) / elapsedTime);

    /* PID summery */
    roll_PID = roll_pid_p + roll_pid_i + roll_pid_d;
    pitch_PID = pitch_pid_p + pitch_pid_i + pitch_pid_d;


    /* Acceleromteter PID summery */
    accX_PID = accX_pid_p + accX_pid_i + accX_pid_d;
    accY_PID = accY_pid_p + accY_pid_i + accY_pid_d;

    /* Regulate PID output for ESCs */
    if (roll_PID < -400) {
      roll_PID = -400;
    }
    if (roll_PID > 400) {
      roll_PID = 400;
    }
    if (pitch_PID < -400) {
      pitch_PID = -400;
    }
    if (pitch_PID > 400) {
      pitch_PID = 400;
    }


    /* Regulate Acceleromteter PID */
    if (accX_PID > 20) {
      accX_PID = 20;
    }
    if (accY_PID > 20) {
      accY_PID = 20;
    }
    if (accY_PID < -20) {
      accY_PID = -20;
    }

    /* Set desired angle for Accelerometer stabilization */
    if (roll_desired_angle == 0) {
      roll_desired_angle = accX_PID;
    }
    if (pitch_desired_angle == 0) {
      pitch_desired_angle = accY_PID;
    }

    /* Set the throttle PID for each motor */
    pid_throttle_R_F = input_throttle + roll_PID - pitch_PID;
    pid_throttle_L_F = input_throttle - roll_PID - pitch_PID;
    pid_throttle_R_B = input_throttle + roll_PID + pitch_PID;
    pid_throttle_L_B = input_throttle - roll_PID + pitch_PID;

    /* Regulate throttle for ESCs */
    //Right front
    if (pid_throttle_R_F < 1100)
    {
      pid_throttle_R_F = 1100;
    }
    if (pid_throttle_R_F > 2000)
    {
      pid_throttle_R_F = 2000;
    }

    //Left front
    if (pid_throttle_L_F < 1100)
    {
      pid_throttle_L_F = 1100;
    }
    if (pid_throttle_L_F > 2000)
    {
      pid_throttle_L_F = 2000;
    }

    //Right back
    if (pid_throttle_R_B < 1100)
    {
      pid_throttle_R_B = 1100;
    }
    if (pid_throttle_R_B > 2000)
    {
      pid_throttle_R_B = 2000;
    }

    //Left back
    if (pid_throttle_L_B < 1100)
    {
      pid_throttle_L_B = 1100;
    }
    if (pid_throttle_L_B > 2000)
    {
      pid_throttle_L_B = 2000;
    }

    /* Save Previous Error */
    roll_previous_error = roll_error;
    pitch_previous_error = pitch_error;

    /* Save Acceleromteter Previous Error */
    accX_previous_error = accX_error;
    accY_previous_error = accY_error;


    Serial.println(input_throttle);

    if (input_throttle < 1100) {
      pid_throttle_L_F = input_throttle;
      pid_throttle_L_B = input_throttle;
      pid_throttle_R_F = input_throttle;
      pid_throttle_R_B = input_throttle;

      roll_error = 0;
      pitch_error = 0;
      roll_previous_error = 0;
      pitch_previous_error = 0;
    }

    motor_LF.writeMicroseconds(pid_throttle_L_F);
    motor_RF.writeMicroseconds(pid_throttle_R_F);
    motor_LB.writeMicroseconds(pid_throttle_L_B);
    motor_RB.writeMicroseconds(pid_throttle_R_B);

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);

    blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
  }
}

Thanks beforehand!
Best regards Max

Your post was MOVED to it's current location as it is more suitable.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

You write an int, but try to receive a c-string, that can not work.
The radio will not be available (i.e. have a packet received) 99.9% of the time,
introducing a delay and printing something if that is the case is just crazy.
So your code seems to be copy and pasted crap without any understanding.

Are you sure that both NRFs really work?
Does a register dump after initialization show the correct values?

Do you have a separate power supply for the 3.3V of (at least) the high power module?
A capacitor of about 10 uF across the power pins of the modules often helps.

Sometimes a minimal distance between the modules is needed.

1 Like

Hi, thanks for your response. It is not copied and pasted. The two modules are powered via a AMS1117 3.3 voltage regulator. I have 2 radio values because I will send values back later, but it is only using the 00002 channel. Can I receive an int instead of a char?

What should hinder you?

1 Like

Ok, I will test it out!

There are no "radio values".

You are aware that you can return data with the ACK that is sent anyway?
So there is no need for a second pipe or an explicit switching to transmit mode
for bidirectional communication.

Now it works! Thank you for the help. There was also a wiring issue where I mixed up CE and CS pin.

Btw, how can I send values back without opening another pipe?

The feature is called AckPayload, a basic example can be found in Robin2's tutorial.

You have to preload the packet that should be returned on a reception and put new data in
after a reception, so in a way the communication is one packet behind.
You want to send packet quite often, so that should not be a problem.
Using that mode also enables dynamic payloads, so your packets get smaller and faster.

1 Like

Ok, I will give it a shot! Sorry for spamming new questions but now my MPU6050 outputs 0 0 0 in the values. I communicate with the MPU6050 via I2C, does the NRF interfear with it in any way? Here is my entire flight controller code:

#include <ESC.h>
#include "I2Cdev.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

#include "MPU6050_6Axis_MotionApps20.h"

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

MPU6050 mpu;

ESC motor_LF;
ESC motor_RF;
ESC motor_LB;
ESC motor_RB;

RF24 radio(8, 9);
byte addresses[][6] = {"00001", "00002"};

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13
bool blinkState = false;

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

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

uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

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

int read_input_throttle;
float input_throttle;

/* Valut */
float elapsedTime, time, timePrev;
long loop_timer;

/* Roll PID */
float roll_PID, pid_throttle_L_F, pid_throttle_L_B, pid_throttle_R_F, pid_throttle_R_B, roll_error, roll_previous_error;
float roll_pid_p = 0;
float roll_pid_i = 0;
float roll_pid_d = 0;
/* Roll PID Constants */
double roll_kp = 7;
double roll_ki = 0.006;
double roll_kd = 1.2;
float roll_desired_angle = 0;

/* Pitch PID */
float pitch_PID, pitch_error, pitch_previous_error;
float pitch_pid_p = 0;
float pitch_pid_i = 0;
float pitch_pid_d = 0;
/* Pitch PID Constants */
double pitch_kp = 72;
double pitch_ki = 0.006;
double pitch_kd = 1.22;
float pitch_desired_angle = 0;

/* Accelerometer X PID */
float accX_PID, accX_error, accX_previous_error;
float accX_pid_p = 0;
float accX_pid_i = 0;
float accX_pid_d = 0;
/* Accelerometer X PID Constants */
double accX_kp = 72;
double accX_ki = 0.006;
double accX_kd = 1.22;

/* Accelerometer Y PID */
float accY_PID, accY_error, accY_previous_error;
float accY_pid_p = 0;
float accY_pid_i = 0;
float accY_pid_d = 0;
/* Accelerometer Y PID Constants */
double accY_kp = 72;
double accY_ki = 0.006;
double accY_kd = 1.22;

void setup() {
  Serial.begin(115200);
  while (!Serial);

  radio.begin();

  radio.openReadingPipe(1, addresses[1]);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();

  motor_LF.attach(4);
  motor_RF.attach(5);
  motor_LB.attach(6);
  motor_RB.attach(7);

  motor_LF.writeMicroseconds(1000);
  motor_RF.writeMicroseconds(1000);
  motor_LB.writeMicroseconds(1000);
  motor_RB.writeMicroseconds(1000);

  // join I2C bus (I2Cdev library doesn't do this automatically)
#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 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"));

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

  if (devStatus == 0) {
    // Calibration Time: generate offsets and calibrate our MPU6050
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    mpu.PrintActiveOffsets();
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
    Serial.println(F(")..."));
    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!"));
    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(")"));
  }

  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  if (radio.available()) {
    radio.read(&read_input_throttle, sizeof(read_input_throttle));
    input_throttle = read_input_throttle;

    // if setup fail dont run the program
    if (!dmpReady) return;

    /* Start Timer */
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);

    /* PID */
    roll_error = roll_desired_angle - (ypr[2] * 180 / M_PI);
    pitch_error = pitch_desired_angle - (ypr[1] * 180 / M_PI);

    /* Acceleromteter PID */
    accX_error = 0 - aaReal.x;
    accY_error = 0 - aaReal.y;

    /* Prospect */
    roll_pid_p = roll_kp * roll_error;
    pitch_pid_p = pitch_kp * pitch_error;

    /* Acceleromteter Prospect */
    accX_pid_p = accX_kp * accX_error;
    accY_pid_p = accY_kp * accY_error;

    /* Integral */
    if (-3 < roll_error < 3)
    {
      roll_pid_i = roll_pid_i + (roll_ki * roll_error);
    }
    if (-3 < pitch_error < 3)
    {
      pitch_pid_i = pitch_pid_i + (pitch_ki * pitch_error);
    }

    /* Acceleromteter Integral */
    if (-3 < accX_error < 3)
    {
      accX_pid_i = accX_pid_i + (accX_ki * accX_error);
    }
    if (-3 < accY_error < 3)
    {
      accY_pid_i = accY_pid_i + (accY_ki * accY_error);
    }


    /* Derivate */
    roll_pid_d = roll_kd * ((roll_error - roll_previous_error) / elapsedTime);
    pitch_pid_d = pitch_kd * ((pitch_error - pitch_previous_error) / elapsedTime);


    /* Acceleromteter Derivate */
    accX_pid_d = accX_kd * ((accX_error - accX_previous_error) / elapsedTime);
    accY_pid_d = accY_kd * ((accY_error - accY_previous_error) / elapsedTime);

    /* PID summery */
    roll_PID = roll_pid_p + roll_pid_i + roll_pid_d;
    pitch_PID = pitch_pid_p + pitch_pid_i + pitch_pid_d;


    /* Acceleromteter PID summery */
    accX_PID = accX_pid_p + accX_pid_i + accX_pid_d;
    accY_PID = accY_pid_p + accY_pid_i + accY_pid_d;

    /* Regulate PID output for ESCs */
    if (roll_PID < -400) {
      roll_PID = -400;
    }
    if (roll_PID > 400) {
      roll_PID = 400;
    }
    if (pitch_PID < -400) {
      pitch_PID = -400;
    }
    if (pitch_PID > 400) {
      pitch_PID = 400;
    }


    /* Regulate Acceleromteter PID */
    if (accX_PID > 20) {
      accX_PID = 20;
    }
    if (accY_PID > 20) {
      accY_PID = 20;
    }
    if (accY_PID < -20) {
      accY_PID = -20;
    }

    /* Set desired angle for Accelerometer stabilization */
    if (roll_desired_angle == 0) {
      roll_desired_angle = accX_PID;
    }
    if (pitch_desired_angle == 0) {
      pitch_desired_angle = accY_PID;
    }

    /* Set the throttle PID for each motor */
    pid_throttle_R_F = input_throttle + roll_PID - pitch_PID;
    pid_throttle_L_F = input_throttle - roll_PID - pitch_PID;
    pid_throttle_R_B = input_throttle + roll_PID + pitch_PID;
    pid_throttle_L_B = input_throttle - roll_PID + pitch_PID;

    /* Regulate throttle for ESCs */
    //Right front
    if (pid_throttle_R_F < 1100)
    {
      pid_throttle_R_F = 1100;
    }
    if (pid_throttle_R_F > 2000)
    {
      pid_throttle_R_F = 2000;
    }

    //Left front
    if (pid_throttle_L_F < 1100)
    {
      pid_throttle_L_F = 1100;
    }
    if (pid_throttle_L_F > 2000)
    {
      pid_throttle_L_F = 2000;
    }

    //Right back
    if (pid_throttle_R_B < 1100)
    {
      pid_throttle_R_B = 1100;
    }
    if (pid_throttle_R_B > 2000)
    {
      pid_throttle_R_B = 2000;
    }

    //Left back
    if (pid_throttle_L_B < 1100)
    {
      pid_throttle_L_B = 1100;
    }
    if (pid_throttle_L_B > 2000)
    {
      pid_throttle_L_B = 2000;
    }

    /* Save Previous Error */
    roll_previous_error = roll_error;
    pitch_previous_error = pitch_error;

    /* Save Acceleromteter Previous Error */
    accX_previous_error = accX_error;
    accY_previous_error = accY_error;


    Serial.println(input_throttle);

    if (input_throttle < 1100) {
      pid_throttle_L_F = input_throttle;
      pid_throttle_L_B = input_throttle;
      pid_throttle_R_F = input_throttle;
      pid_throttle_R_B = input_throttle;

      roll_error = 0;
      pitch_error = 0;
      roll_previous_error = 0;
      pitch_previous_error = 0;
    }

    motor_LF.writeMicroseconds(pid_throttle_L_F);
    motor_RF.writeMicroseconds(pid_throttle_R_F);
    motor_LB.writeMicroseconds(pid_throttle_L_B);
    motor_RB.writeMicroseconds(pid_throttle_R_B);

    
  } 
}

Thanks beforehand!

No, I have not seen any problems with I2C.

Btw "interfear" is a nice word creation that sparks imagination.

1 Like

When I test it with the I2Cdev library for MPU6050 it works perfectly, but I had it implemented in my program before I implemented the NRF, and now it only outputs zeros, here is the program for testing th I2C library:

// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2019-07-08 - Added Auto Calibration and offset generator
//		   - and altered FIFO retrieval sequence to avoid using blocking code
//      2016-04-18 - Eliminated a potential infinite loop
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

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

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */



// 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)
//#define OUTPUT_READABLE_QUATERNION

// 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)
//#define OUTPUT_READABLE_EULER

// 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)
#define OUTPUT_READABLE_YAWPITCHROLL

// 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.
//#define OUTPUT_READABLE_REALACCEL

// 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.
//#define OUTPUT_READABLE_WORLDACCEL

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



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

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
    // 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();
    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) {
        // Calibration Time: generate offsets and calibrate our MPU6050
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        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);
}



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

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;
    // read a packet from FIFO
    if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet 
        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

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

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // 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);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif
    
        #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
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

In my brain it should work in my code, but I dont know why it goes through initzialation and still outputs zeros.

This is my output from the serial monitor:

1253.00
ypr	180.00	0.00	0.00
1253.00
ypr	180.00	0.00	0.00
1253.00
ypr	180.00	0.00	0.00
1253.00
ypr	180.00	0.00	0.00
1253.00
ypr	180.00	0.00	0.00
1253.00
ypr	180.00	0.00	0.00

I think the closing bracket of that if is in the wrong place.

Witch bracket? I checked it and they both close at the bottom.

I found the error! I forgot to grab the latest fifoBuffer before reading it! Thanks for all the help, its really appriciated!

So you really only want to run your PID if a packet was received?
Sounds strange...

Oh, you have a point there. I didnt think of that, or I want the drone to fly only when my transmitter is in range. Now im just trying to figure out the throttle for each motor, but they behave strange. I try to make this work:

      pid_throttle_R_F = input_throttle + roll_PID - pitch_PID;
      pid_throttle_L_F = input_throttle - roll_PID - pitch_PID;
      pid_throttle_R_B = input_throttle + roll_PID + pitch_PID;
      pid_throttle_L_B = input_throttle - roll_PID + pitch_PID;

I have no expertise in drone control, sorry.