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 !


