Self balance Robot one wheel doesn't work

Good day

I am trying to build a Self Balance Robot based on the previous self-balance robots I have seen and studied on the internet, but I can't figure out why one of the motor does not rotate synchronously with the other one. For example, case 1, when I position the robot in Slant or lean forward, both motors rotate Counterclockwise (CCW) as it should be. In case 2 where it is my current problem, I slant or lean backward the robot, one of the motors rotates correctly Clockwise (CW), while the other one stops completely. From what I have understand, case 1 and case 2 should have the opposite result

#include <PID_v1.h>
#include <LMotorController.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

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

#define MIN_ABS_SPEED 20

MPU6050 mpu;

// 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
VectorFloat gravity;    // [x, y, z]            gravity vector
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

//PID
double originalSetpoint = 175.8;
double setpoint = originalSetpoint;
double movingAngleOffset = 0.1;
double input, output;
int moveState=0; //0 = balance; 1 = back; 2 = forth
double Kp = 50; // first - proportional, generates a response that is proportional to the angle of inclination error.
double Kd = 1.4; // second - derivative, the difference between the current error and the previous error divided by the 
                    //sampling period. This acts as a predictive term that responds to how the robot might behave 
                    // in the next sampling loop
double Ki = 60; // third - integral, the sum of all the errors multiplied by the sampling period. This is a response 
                    // based on the behavior of the system in past.
PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

double motorSpeedFactorLeft = 1;
double motorSpeedFactorRight = 1;
//MOTOR CONTROLLER

// Right
int ENA = 10;
int IN1 = 8; // to rotate in same direction
int IN2 = 9;

// Left
int IN3 = 7;
int IN4 = 6;
int ENB = 5;
LMotorController motorController(ENA, IN1, IN2, ENB, IN3, IN4, motorSpeedFactorLeft, motorSpeedFactorRight);

//timers
long time1Hz = 0;
long time5Hz = 0;

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


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

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

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

    // 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();
        
        //setup PID
        
        pid.SetMode(AUTOMATIC);
        pid.SetSampleTime(10);
        pid.SetOutputLimits(-255, 255);  
    }
    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(")"));
    }
}


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)
    {
        //no mpu data - performing PID calculations and output to motors
        
        pid.Compute();
        motorController.move(output, MIN_ABS_SPEED);
        
    }

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

        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        #if LOG_INPUT
            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
        input = ypr[1] * 180/M_PI + 180;
   }
}

Please post proper schematics. It's no help showing that the boards are red or green, and rectangular.
Which functions do those mystery pins have that are connected?

1 Like

When you post the schematic as how you have wired it please include links to the hardware items as well. Be sure they give technical information on the parts. Links to sales outlets like azon are useless. Sorry you wasted your time on the frizzy picture, it is useless for troubleshooting and or design.

Hi,
Have you written some code that just operates your motors?
If not then;
STOP and write some simple code that just operates your motors so you can prove your hardware.

Did you write your code in stages and get each stage working before starting the next, then putting them together one at a time, each time getting the bugs out before adding the next stage?

Tom... :smiley: :+1: :coffee: :australia:

Hello,
I have tried troubleshooting every parts i have used. I even tried using the code below

// Motor Checker
// Right Motor
int enA = 10;
int in1 = 9;
int in2 = 8;

// Left Motor
int in3 = 6;
int in4 = 7; // to rotate in one direction
int enB = 5;

void setup() 
{
  // put your setup code here, to run once:
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  pinMode(enB, OUTPUT);

}

void loop() 
{
  // put your main code here, to run repeatedly:
  analogWrite(enA, 250);
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  digitalWrite(in3,HIGH);
  digitalWrite(in4,LOW);
  analogWrite(enB, 250);
}

to check if both motors are okay. They are both running at the same directions. I also did troubleshoot the gyroscope and they are fine. For the code part, I just understand and copied from the self balancing robot i have seen on the internet. Just Modified the ENA, IN1, IN2, IN3, IN4, ENB pins.

Have you checked that particular motor separately? Detaching from the circuit?

That sounds right, so put Serial.print() statements in the code to see what goes wrong.

Do the direction variables have the values that you expect them to have?


Apologize. Im new to this forum. And it seems because I'm a newbie, there is a limit of 2 links per post, so I'm just gonna put the materials here:

  • L - Shape Battery Operated (BO) Motor
  • L298N Motor Driver
  • Batteries - Fritzing doesnt have 6 AA Battery figure but I have used 6 AA Eneloop with 1.2 V min. 1900mAh Batteries each
  • Arduino Nano
  • MPU6050

I hope this can help

I have now replied with the other comments. Can you check?

Yes, I have checked it multiple times with my Motor Checker trouble shooter and they are both working.

Can you kindly edit the code yourself and upload-reply? I cant seem to understand what are you referring and the place it should be placed.

No, as the problem is not very interesting to me. I'm just recommending to use a standard "debugging" technique, which also helps you to understand how the code is working, or not.

If you do not want to put some effort into understanding and fixing the code and/or wiring, consider posting on the Jobs and Paid Collaboration forum section.

Didn't You read reply #3?
Those coloured pieces of art not useful. The pin designations are interesting, not the physical position on the circuit. You can't expect helpers to pick up datasheets for the circuits used, to figure the pin names and draw the schematics.
Is 6 * 1.2 volt enough for the voltage converter on the L298?
Let's hope other helpers pinpoint the issue.....

Have you checked in forward and reverse motor directions?

Can you please post some pictures of your project so we can see your component layout?

Tom... :smiley: :+1: :coffee: :australia:

I think your battery is not suppling sufficient current.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.