PID issue with a self balancing robot

Hello everyone,

I'm trying to build a self balancing robot by myself.
For the electronics I took the schematic of this video :https://www.youtube.com/watch?v=WHdJEUPJojo&t=315s

But I have a MPU6050.
The issue is that I have 2 motors that works well but I try with the esp32 to send them pwm based on 0-4095, and when the duty cycle is < 1400 no motors move and so when I try to implement the PID beginning by the P, I can't get any solution that are correct.

I try to implement a bigger battery with a higher voltage and it do the same.

If someone knows if it is the code of the PID or the motor that I need to change or have any idea of the solution it would be great !

In case : I have a PWM frequency of 7000 and a PWM resolution of 12

Here is the code :

Here are the constant :

#include "main.h"

// Global variables: replaced pointer declarations with simple floats.
float RateRoll = 0;
float RatePitch = 0;
float GyroRoll = 0;
float GyroPitch = 0;
float globalAngleRoll = 0;
float gyroBiasRoll = 0, gyroBiasPitch = 0, gyroBiasYaw = 0;
bool calibrated = false;

// Global variables: variable for the gyroscope and accelerometer
float gyroX,gyroY,gyroZ;
float accX, accY, accZ;
float acc_angle_y,acc_angle_x;
float total_angle_x, total_angle_y;
float gyroXerror = 0.07;
float gyroYerror = 0.03;
float gyroZerror = 0.01;


String gyroReading;
String accReading;


Adafruit_MPU6050 mpu;

// Global variables: variable for time differencies
unsigned long last_time =0;
unsigned long now = 0;
unsigned long dt = 0;
unsigned long lastSignalTime = 0;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Create an Event Source on /events
AsyncEventSource events("/events");

// Json Variable to Hold Sensor Readings
JSONVar readings;

Then I use this function to read the signal of the accelerometer :


// return the rad / s 
void gyro_signal(){
  sensors_event_t accel, gyro, temp;
  mpu.getEvent(&accel, &gyro, &temp);

  now = millis(); // get the time 
  dt = (now -lastSignalTime); // time differencies for the angle
  if(dt == 0) return;
  float gx = gyro.gyro.x - gyroBiasRoll;
  float gy = gyro.gyro.y - gyroBiasPitch;
  float gz = gyro.gyro.z - gyroBiasYaw;
  
  // Debug: print raw values
  //  Serial.printf("dt:%.f  now:%.lu  lastSignal:%.lu  gyroX:%.1f  \n" ,RAD_TO_DEG*(float)dt/1000, now, lastSignalTime, gyroX);

  // Remove threshold conditions for debugging
  float dt_s = (float)dt*0.001f;
  gyroX += gx* dt_s;
  gyroY += gy *dt_s;
  gyroZ += gz* dt_s;

  // get the accelerometer values 
  accX = accel.acceleration.x;
  accY = accel.acceleration.y;
  accZ = accel.acceleration.z;

  // Acceleration angles 
  acc_angle_x = (atan((accY)/sqrt(pow(accX,2) + pow(accZ,2))));//atan2(accY, accZ); //
  acc_angle_y = (atan(-1*(accX)/sqrt(pow(accY,2) + pow(accZ,2)))); //atan2(-accX, sqrt(accY*accY + accZ*accZ));

  // Total angle and filter 
  total_angle_x = 0.98f * (total_angle_x + gx*dt_s) + 0.02f * acc_angle_x;
  total_angle_y = 0.98f * (total_angle_y + gy*dt_s) + 0.02f * acc_angle_y;

  lastSignalTime = now;
}


This is the **PID function**  :

```cpp
float PID(float current_angle){
  // Error - Proportionnal
  if(dt == 0){return motorInput;}
  float dt_s = (float)dt * 0.001f;

  float error = target_angle-current_angle;

  /**/
  // Integral term
  integral += error*dt_s;
  integral = constrain(integral, -MAX, MAX);   // anti-wind-up

  // Derivate turm 
  float derivate = (current_angle - oldvalue) / dt_s;
  oldvalue = current_angle;

  float result_PID = (error*Kp) + (integral*Ki) + (derivate*Kd);

  result_PID = constrain(result_PID,-MAX + 200,MAX - 200 ); // reserve output due to the non movement ( controller input)
  /*if( result_PID < 1000 && result_PID >=0){
    result_PID = 1000;
  }
  else if(result_PID <=0 && result_PID > -1000){
    result_PID = -1000;
  }*/
  return result_PID;
}

There is the function I use to make the right motor ( left as well ) turn in a direction or the other based on the PID math :


void rightMotorSpeed(int motor_input){
  if(previous_speed * motor_input <0 || motor_input == 0){
    digitalWrite(RIGHT_MOTOR_ENA_1,LOW);
    ledcWrite(0,0);
    ledcWrite(1,0);
    digitalWrite(RIGHT_MOTOR_ENA_2,LOW);
    delayMicroseconds(300);
  }
  int pwm = constrain(abs(motor_input), 0, 4095);
  if (pwm > 0 && pwm < 1000) {
    pwm = 1000;  // seuil minimal pour vaincre la friction
  }
  if(motor_input > 0){
    digitalWrite(RIGHT_MOTOR_ENA_1,HIGH);
    ledcWrite(0,pwm);
  }
  else{
    digitalWrite(RIGHT_MOTOR_ENA_2,HIGH);
    ledcWrite(1,pwm);
  }
}

And this is the setup and loop function :


void setup() {
  // Initialisation of the modules
  Serial.begin(115200);
  initIMU();
  calibrateGyro();
  lastSignalTime = millis();
  //initWiFi();
  //initLittleFS();

  // pinMode motors 
  pinMode(RIGHT_MOTOR_ENA_1,OUTPUT);
  pinMode(RIGHT_MOTOR_ENA_2,OUTPUT);
  pinMode(LEFT_MOTOR_ENA_1,OUTPUT);
  pinMode(LEFT_MOTOR_ENA_2,OUTPUT);
  pinMode(LEFT_MOTOR_PWM_1,OUTPUT);
  pinMode(RIGHT_MOTOR_PWM_1,OUTPUT);
  pinMode(LEFT_MOTOR_PWM_2,OUTPUT);
  pinMode(RIGHT_MOTOR_PWM_2,OUTPUT);

  // Setup PWM channel
  ledcSetup(0, PWM_Frequency, PWM_Resolution);
  ledcSetup(1, PWM_Frequency, PWM_Resolution);
  ledcSetup(2, PWM_Frequency, PWM_Resolution);
  ledcSetup(3, PWM_Frequency, PWM_Resolution);

  // Attach PWM channel 
  ledcAttachPin(RIGHT_MOTOR_PWM_1, 0);
  ledcAttachPin(RIGHT_MOTOR_PWM_2, 1);
  ledcAttachPin(LEFT_MOTOR_PWM_1, 2);
  ledcAttachPin(LEFT_MOTOR_PWM_2, 3);

  // Setup level motors
  digitalWrite(RIGHT_MOTOR_ENA_1,0);
  ledcWrite(0,0);
  ledcWrite(1,0);
  digitalWrite(RIGHT_MOTOR_ENA_2,0);

  digitalWrite(LEFT_MOTOR_ENA_1,0);
  ledcWrite(2,0);
  ledcWrite(3,0);
  digitalWrite(LEFT_MOTOR_ENA_2,0);
}

void loop() {
  if (!calibrated) {
      calibrateGyro();
  }
  // Acquisition of the angles
  gyro_signal();

  //PID values 
  motorInput = PID(total_angle_y);
  Serial.printf("MotorInput / Speed : %f\n",motorInput);
  rightMotorSpeed(motorInput);
  leftMotorSpeed(motorInput);
  previous_speed =  motorInput;
}

Thanks in advance !

What's that in percent?

Use higher values to make the motors move.

First, thanks for the response.

It correspond to 34% of the maximum duty cycle.

I try with a if statement that make the duty cycle to 1500 if the PID math is <=1500.

The issue is that there is no progression with the power of the motors and there is too much power in they that make the robot fall everytime.

Even if I calculate only the proportionnal.

I don't see how can I put more power, if I do so the robot falls directly.

Adding a minimum duty cycle may help?

Do you use a L29x based motor driver?

That probably has to do with the circuit diagram you forgot to post, the components you chose, and how you wired everything. For help, post the required details, with links to the components and a photo of the setup.

I don't use a component made, I made my own H-bridge based on the video : https://www.youtube.com/watch?v=WHdJEUPJojo&t=214s

So I use 2 digital mosfet to enable the direction and then with 2 analog mosfet I use a PWM value to make the power for the directions

This schematic is build for 1 side, so I have another one for the other side.

The only issue ( but I don't fix that this is the problem because the problem is the same in the right and left side ), is that one on the condensator is a 10uF because I misscommand the number of the condensator.

This is the component list :


Don't do that!

DC motors are happy with unfiltered PWM.

Okay I didn't know. The thing is that with the video with the link up, he uses this functionnality that works well.

Secondly when I change the motor by a voltmeter and I choosed with the "cin" instruction a pwm value and adapt the direction and it did well on the voltmeter and it corresponds to the correct voltage.

So do I need to change the motors ? How is that possible that I have the correct voltage when I take a voltmeter, but the motors are not activating with a duty cycle < 34% and when I put them directly into a DC DC generator with a voltage equivalent to this 34% it works well ?

DC motors do not simply behave like you think.

Either you

  • start learning more about DC motors and controllers in time space
  • or you add a speed sensor to each motor
  • or you replace the motors by easy controlled and well behaved BLDC or stepper motors.

The choice is up to you...

That general behavior is always the case, and it is not a problem with a properly tuned PID controller.

However, the 34% value is higher than usual. A poorly designed or improperly constructed H-bridge is an obvious suspect. PWM frequency is another and choice of motor is a third.

the top mosfets are the wrong type...

When you say the PWM frequency is wrong, what do you recommend ?

And my motors have 5 years, do you think is that a possibility that time damaged them ?

I don't understand, can you explain why ?

they should be P channel... N channel mosfets cannot be fully opened in your configuration.

Experiment to learn how the motor works with different PWM frequencies. There can be a huge effect, depending on motor inductance.

Not true if the gate driver chip is correctly configured. It uses capacitive boost to increase the gate drive voltage well above Vdd.

But it is silly for the OP to believe that because one youtuber posted a video showing a project working successfully that all aspects of the project design and construction are correct, or even work as shown.

Okay, agreed. I did not dig in far enough...