Loop with two DC motors

Hi, my project is to control the robot to move forward, left, right, and backward. Robot need to move forward at all time at 0degree. If the robot moves 15degree offset, the gyro sensor will set motor back to 0degree. The problem now is, I cant move left or right because the gyro keeps the robot at 0degree. How can I loop forward direction, left direction, right direction separately?

tq in advance

#include "I2Cdev.h"
#include <AFMotor.h>
#include "MPU6050_6Axis_MotionApps20.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
AF_DCMotor motor1(1, MOTOR12_8KHZ); // create motor #1, 8KHz pwm
AF_DCMotor motor2(2, MOTOR12_8KHZ); // create motor #2, 8KHz pwm
AF_DCMotor motor3(3, MOTOR34_8KHZ); // create motor #3, 8KHz pwm

MPU6050 mpu;

#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();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

Serial.begin(9600);
    mpu.initialize();
    devStatus = mpu.dmpInitialize();
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1688); // 1688 factory default for my test chip

if (devStatus == 0) {
     
        mpu.setDMPEnabled(true);

attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();     
   
        dmpReady = true;

packetSize = mpu.dmpGetFIFOPacketSize();
    } else {

}

pinMode(LED_PIN, OUTPUT);
}
void draw(void) {

Serial.print("MPU 6050");
  Serial.print("YAW  :");Serial.print("\t");
  Serial.print(ypr[0] * 180/M_PI);Serial.print("\t");
  Serial.print("PITCH:");Serial.print("\t");
  Serial.print(ypr[1] * 180/M_PI);Serial.print("\t");
  Serial.print("ROLL :");Serial.print("\t"); 
  Serial.print(ypr[2] * 180/M_PI);Serial.println("\t");
  Serial.print( ypr[0]);

}

void getypr()
{
    if (!dmpReady) return;

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

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

mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
          delay(350);
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
        delay(350);
    }
}

void loop() {
 
draw();
getypr();
bluetooth();  // call bluetooth function
  if((ypr[0] * 180/M_PI>1 && ypr[0] * 180/M_PI<15))
  {           
      Serial.println(" +Less stable");
 
      motor1.run(BACKWARD);
      motor1.setSpeed(200);
      motor2.run(BACKWARD);
      motor2.setSpeed(200);
     
  }
  else if(ypr[0] * 180/M_PI>-15 && ypr[0] * 180/M_PI<-1)
  {           
      Serial.println(" -Less stable");
 
        motor1.run(FORWARD);
        motor1.setSpeed(200);
        motor2.run(FORWARD);
        motor2.setSpeed(200);
  }

else if(ypr[0] * 180/M_PI>-15 && ypr[0] * 180/M_PI<15)
  {           
      Serial.println(" -move right");
 
        motor1.run(RELEASE);
        motor2.run(RELEASE);
    }
}

void bluetooth(){
  while(Serial.available()) {
  delay(100);
  char data=Serial.read();

if(data == '1'){
  Serial.println("Forward");
  forward();
    draw();
  getypr();
 
  if(ypr[0] * 180/M_PI>15 && ypr[0] * 180/M_PI<80)
    {  Serial.println(" -Less stable");
        motor1.run(BACKWARD);
        motor1.setSpeed(150);
        motor2.run(BACKWARD);
        motor2.setSpeed(150);
  }
  else if(ypr[0] * 180/M_PI>-80 && ypr[0] * 180/M_PI<-15)
  {           
        Serial.println(" +Less stable");
        motor1.run(FORWARD);
        motor1.setSpeed(150);
        motor2.run(FORWARD);
        motor2.setSpeed(150);
  } 
  delay(50);
  }
    else if (data =='2'){
    Serial.println("Left");
    left();
    delay(50);
  }
  else if (data =='3'){
    Serial.println("Right");
    right();
    delay(50);
  }
  else if(data =='4'){
    Serial.println("Backward");
    backward();
    delay(50);
  }
  else if(data =='8'){
    Serial.println("Forward Right");
    forwardright();
    delay(50);
  }
  else if(data =='6'){
    Serial.println("Forward Left");
    forwardleft();
    delay(50);
  }
  else if(data =='7'){
    Serial.println("Back right");
    backright();
    delay(50);
  }
  else if(data =='9'){
    Serial.println("Back left");
    backleft();
    delay(50);
  }
  else if(data =='5'){
    Serial.println("Stop");
    Stop();
    delay(50);
  }
}
}
void forward()
{
  motor1.run(FORWARD);
  motor1.setSpeed(230);
  motor2.run(BACKWARD);
  motor2.setSpeed(230);
  delay(500);
}

void backward()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(230);
  motor2.run(FORWARD);
  motor2.setSpeed(230);
  delay(500);
}
void Stop()
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(500);

}
void left()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(150);
  motor2.run(BACKWARD);
  motor2.setSpeed(150);
//  motor3.run(BACKWARD);
//  motor3.setSpeed(255);
  delay(500);
}
void right()
{

motor1.run(FORWARD);
  motor1.setSpeed(150);
  motor2.run(FORWARD);
  motor2.setSpeed(150);
//  motor3.run(FORWARD);
// motor3.setSpeed(255);
  delay(500);
}
void forwardright()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(200);
  motor2.run(FORWARD);
  motor2.setSpeed(255);

delay(500);
}
void forwardleft()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(255);
  motor2.run(FORWARD);
  motor2.setSpeed(200);
  delay(500);
}
void backright()
{
  motor1.run(FORWARD);
  motor1.setSpeed(255);
  motor2.run(RELEASE);
  motor3.run(BACKWARD);
  motor3.setSpeed(200);
  delay(500);
}
void backleft()
{
  motor1.run(RELEASE);
  motor2.run(BACKWARD);
  motor2.setSpeed(255);
  motor3.run(FORWARD);
  motor3.setSpeed(255); 
  delay(500);
}

P.S. I have tried placing the sensor reading into void forward but still doesnt work

You should serial print the accel values instead of just terse status messages. The answer is probably in those values.

You need to separate out the different parts of your code. For example in your bluetooth() function you get data, you check your MPU and you move the motors.

The bluetooth() function should just get the bluetooth data and save it.

Only call the getypr() function from loop().

Then you need a function (also called from loop() ) that looks at the available data from bluetooth and from the MPU and decides what motor function(s) should be called.

By separating the activities like this each part can be tested separately.

PLUS what @aarg has said

...R
Planning and Implementing a Program

Thanks for the response guys. I hve tried this code, the robot is able to move back when its >7degree. but it doesnt stop when angle is >-7degree && <7degree

void loop() {
  
get_raw_6axis();
gx=map(gx,-17000,17000,-1500,1500);  
draw();
getypr();
bluetooth();  // call bluetooth function
}

void bluetooth(){
  while(Serial.available()) {
  delay(100);
  char data=Serial.read();

 if(data == '1'){
  Serial.println("Forward");
  forward();
  
  if(ypr[0] * 180/M_PI>15 && ypr[0] * 180/M_PI<80)
    {  Serial.println(" -Less stable");
        motor1.run(BACKWARD);
        motor1.setSpeed(110);
        motor2.run(BACKWARD);
        motor2.setSpeed(110);
    }
  else if(ypr[0] * 180/M_PI>-80 && ypr[0] * 180/M_PI<-15)
   {            
      Serial.println(" +Less stable");
        motor1.run(FORWARD);
        motor1.setSpeed(110);
        motor2.run(FORWARD);
        motor2.setSpeed(110);
   }  
   else if()
   {            
      motor1.run(FORWARD);
     motor1.setSpeed(230);
     motor2.run(BACKWARD);
     motor2.setSpeed(230);

    
   }  
  delay(50);
  }
    else if (data =='2'){
     Serial.println("Left");
     left();
   if(ypr[0] * 180/M_PI>15 && ypr[0] * 180/M_PI<80)
    {  Serial.println(" -Less stable");
        motor1.run(BACKWARD);
        motor1.setSpeed(190);
        motor2.run(BACKWARD);
        motor2.setSpeed(190);
   }
  else if(ypr[0] * 180/M_PI>-80 && ypr[0] * 180/M_PI<-15)
   {            
      Serial.println(" +Less stable");
        motor1.run(FORWARD);
        motor1.setSpeed(150);
        motor2.run(FORWARD);
        motor2.setSpeed(150);
   } 
  else ()
   {            
      Serial.println(" stable");
    motor1.run(BACKWARD);
  motor1.setSpeed(150);
  motor2.run(BACKWARD);
  motor2.setSpeed(150);
   } 
    delay(50);
  }
  else if (data =='3'){
    Serial.println("Right");
    right();
    
    delay(50);
  }
  else if(data =='4'){
    Serial.println("Backward");
    backward();
    delay(50);
  }
  else if(data =='8'){
    Serial.println("Forward Right");
    forwardright();
    delay(50);
  }
  else if(data =='6'){
    Serial.println("Forward Left");
    forwardleft();
    delay(50);
  }
  else if(data =='7'){
    Serial.println("Back right");
    backright();
    delay(50);
  }
  else if(data =='9'){
    Serial.println("Back left");
    backleft();
    delay(50);
  }
  else if(data =='5'){
    Serial.println("Stop");
    Stop();
  if(ypr[1] * 180/M_PI>7 )
    {  Serial.println(" +Less stable");
        motor1.run(FORWARD);
        motor1.setSpeed(190);
        motor2.run(BACKWARD);
        motor2.setSpeed(190);
   }
  else if(ypr[1] * 180/M_PI<-7)
   {            
      Serial.println(" -Less stable");
        motor1.run(BACKWARD);
        motor1.setSpeed(190);
        motor2.run(FORWARD);
        motor2.setSpeed(190);
   } 
   else
   {
        motor1.run(RELEASE);
        motor2.run(RELEASE);
   }
    
    delay(50);
  }
 }
}
void forward()
{
  motor1.run(FORWARD);
  motor1.setSpeed(230);
  motor2.run(BACKWARD);
  motor2.setSpeed(230);
  delay(500);
}

void backward()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(230);
  motor2.run(FORWARD);
  motor2.setSpeed(230);
  delay(500);
}
void Stop()
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(500); 
}
void left()
{
  motor1.run(BACKWARD);
  motor1.setSpeed(150);
  motor2.run(BACKWARD);
  motor2.setSpeed(150);

  delay(500);
 }
void right()
{

  motor1.run(FORWARD);
  motor1.setSpeed(150);
  motor2.run(FORWARD);
  motor2.setSpeed(150);
//  motor3.run(FORWARD);
 // motor3.setSpeed(255);
  delay(500);
}

}

}

}

kautham:
Thanks for the response guys. I hve tried this code,

You still have loads of non-bluetooth stuff in your bluetooth() function

...R

Thank you Robin2.