Inverted pendulum issues

Hello and thank you for taking your time to read this.

I have built an inverted pendulum robot. It is composed of three platforms made of plexiglass spaced 50mm apart, using 4 8mm threads.
I have confirmed that the motors behave as they should and that the accelerometer works fine through the use of the serial monitor.
The electronics are as follows: Arduino Nano ESP32, the drivers for the motors are a4998 and the motors are NEMA17, powered by a 2Ah 12.4V battery pack. The motor drivers have had their current limit set properly, the wheels spin fine.

The issue is the following: I believe that the robot is too heavy because when i begin tuning the PID regulator, no matter how high I set the P term the robot never self balances itself. It just jitters. It "almost" balances itself, making me to believe it is too heavy.

#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <AccelStepper.h>
#include <PID_v1.h>

Adafruit_MPU6050 mpu;

int MPU_addr = 0x68;

float const_calib_X = 0 ;
float const_calib_Y = 0 ;
float const_calib_Z = 0.2;

#define dirPin_X  2
#define stepPin_X 5

#define dirPin_Y  3  //3 Y //4 Z
#define stepPin_Y 6  //6 Y //7 Z

#define enablePin 8

//PID
double Kp = 100;
double Ki = 0;
double Kd = 0;

double input=0;
double output=0;
double setpoint=0;

PID myPID(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

float unghi; //trimite valoarea unghiului de la accelerometru

const int stepsPerRevolution = 200;  
const int pulsesPerRevolution = 200;

int motorSpeed1;
int motorSpeed2;

unsigned long prevMillis = 0;
int revolutions = 0;

int led_R = 14;
int led_G = 15;
int led_B = 16;

float RateRoll, RatePitch, RateYaw;
float RateCalibrationRoll, RateCalibrationPitch, RateCalibrationYaw;
int RateCalibrationNumber;
float AccX, AccY, AccZ;
float AngleRoll, AnglePitch;
uint32_t LoopTimer;
float KalmanAngleRoll=0, KalmanUncertaintyAngleRoll=2*2;
float KalmanAnglePitch=0, KalmanUncertaintyAnglePitch=2*2;
float Kalman1DOutput[]={0,0};

int raspuns_PID = 0;

// AccelStepper instante
AccelStepper stepper1(1, stepPin_X, dirPin_X);
AccelStepper stepper2(1, stepPin_Y, dirPin_Y);

// FIlter smoothing angle
const float alpha_angle_filter = 1;

// MPU
float filteredAngleRoll = 0.0;
float filteredAnglePitch = 0.0;

//Deadzone for moverobot()
double deadzone = 1;

 void gyro_signals() {
  Wire.beginTransmission(0x68);
  Wire.write(0x1A);
  Wire.write(0x05);
  Wire.endTransmission();
 
  Wire.beginTransmission(0x68);
  Wire.write(0x1C);
  Wire.write(0x10);
  Wire.endTransmission();
 
  Wire.beginTransmission(0x68);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0x68, 6);
 
  int16_t AccXLSB = Wire.read() << 8 | Wire.read();
  int16_t AccYLSB = Wire.read() << 8 | Wire.read();
  int16_t AccZLSB = Wire.read() << 8 | Wire.read();
 
  Wire.beginTransmission(0x68);
  Wire.write(0x1B);
  Wire.write(0x8);
  Wire.endTransmission();    
 
  Wire.beginTransmission(0x68);
  Wire.write(0x43);
  Wire.endTransmission();
 
  Wire.requestFrom(0x68, 6);
 
  int16_t GyroX = Wire.read() << 8 | Wire.read();
  int16_t GyroY = Wire.read() << 8 | Wire.read();
  int16_t GyroZ = Wire.read() << 8 | Wire.read();
 
  RateRoll = (float)GyroX / 65.5;
  RatePitch = (float)GyroY / 65.5;
  RateYaw = (float)GyroZ / 65.5;
 
  AccX = (float)AccXLSB / 4096;
  AccY = (float)AccYLSB / 4096;
  AccZ = (float)AccZLSB / 4096 - const_calib_Z;

  AngleRoll = atan(AccY / sqrt(AccX * AccX + AccZ * AccZ)) * 1 / (3.142 / 180);
  AnglePitch = -atan(AccX / sqrt(AccY * AccY + AccZ * AccZ)) * 1 / (3.142 / 180);

  filteredAngleRoll = alpha_angle_filter * AngleRoll + (1 - alpha_angle_filter) * filteredAngleRoll;
  filteredAnglePitch = alpha_angle_filter * AnglePitch + (1 - alpha_angle_filter) * filteredAnglePitch;
}


void moveRobot()
{


if (filteredAngleRoll > deadzone) {
    // Move forward
    motorSpeed1 = raspuns_PID ;
    motorSpeed2 = -raspuns_PID ;
    stepper1.setSpeed(motorSpeed1);
    stepper2.setSpeed(motorSpeed2);
    stepper1.runSpeed();
    stepper2.runSpeed();
 
} else if (filteredAngleRoll < -deadzone) {
    // Move backward
    motorSpeed1 = -raspuns_PID ;
    motorSpeed2 = raspuns_PID ;
    stepper1.setSpeed(motorSpeed1);
    stepper2.setSpeed(motorSpeed2);
    stepper1.runSpeed();
    stepper2.runSpeed();
 
} else {
    // Stop if input (AngleRoll) is within the deadzone
    stepper1.setSpeed(0);
    stepper2.setSpeed(0);
    motorSpeed1 = 0 ;
    motorSpeed2 = 0 ;
    stepper1.runSpeed();
    stepper2.runSpeed();
}


}


void setup() {

  pinMode(led_R,OUTPUT);
  pinMode(led_G,OUTPUT);
  pinMode(led_B,OUTPUT);
 
  //KALMAN+MPU START
  Serial.begin(115200);
  // while (!Serial);
 
  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
      digitalWrite(led_R,HIGH);
  }
  Serial.println("Found a MPU6050 sensor");
 
  for (RateCalibrationNumber=0; RateCalibrationNumber<2000; RateCalibrationNumber ++) {
    gyro_signals();
    RateCalibrationRoll+=RateRoll;
    RateCalibrationPitch+=RatePitch;
    RateCalibrationYaw+=RateYaw;
    delay(1);
  }
  RateCalibrationRoll/=2000;
  RateCalibrationPitch/=2000;
  RateCalibrationYaw/=2000;
  LoopTimer=micros();
  // KALMAN+MPU FINISH

  //CNC SHIELD
  pinMode(enablePin, OUTPUT);  
  digitalWrite(enablePin, LOW); //LOW=PORNIT

  //MOTORS
  pinMode(stepPin_X, OUTPUT);
  pinMode(dirPin_X, OUTPUT);
  pinMode(stepPin_Y, OUTPUT);
  pinMode(dirPin_Y, OUTPUT);
 
  stepper1.setMaxSpeed(1000);
 
  stepper2.setMaxSpeed(1000);
 
  pinMode(led_R,OUTPUT);
  pinMode(led_G,OUTPUT);
  pinMode(led_B,OUTPUT);

  myPID.SetMode(AUTOMATIC);
  myPID.SetOutputLimits(-1000, 1000);
 
}


void loop() {

  gyro_signals();

  double setpoint = 0;

  input = abs(filteredAngleRoll);

  myPID.Compute();

  raspuns_PID = static_cast<int>(output);
 
  moveRobot();

}



Thank you very much. I also found another problem with my robot. The wheels were slipping, I will drill some holes into the motor shafts in order to fix the wheels to the shafts with some screws.
I have one more question, to serve as a guideline, would you say that the NEMA17's are good enough for a 1.5kg robot?
They state 40 Nm of torque in the datasheet and I am powering them from a 12V 2Ah battery.

This web site has mechanical design theory and calculators for robot vehicles: https://www.societyofrobots.com/

I did not know about this site. There is a lot to learn there and the information is very well laid out.
Thank you for helping me.

40Nm is a beast - NEMA17 steppers without reduction gearing are upto about 0.4Nm hold-in torque, and much much less at speed. You need to use DC gear motor for a balancing robot as you need consistent torque.

The torque required depends on the robots weight, height and wheel radius among other things - can you provide details, and of the actual motors you have?

Hello,

I am sorry for the late response. I have been busy with exams and the robot was put on the back burner.

The wheels are 60mm in diameter, the weight of the robot is 1530 grams and the height is 250mm

I have been playing with the software and confirmed that the PID part is working properly. The wheels are spinning as they should. I used the serial monitor to debug various parameters. I find that the robot is reacting slowly to changes in angle from the setpoint, which is 0,and keeps falling. I also played with various setpoints to account for the center of gravity. I am going to call it quits. While it has been fun and definitely a learning experience it is far above my pay grade, so to speak.

Thank you very much for taking your time to help me. It means a lot to me. It gave me the impulse to start working on the robot again.

I have worked on the code today and implemented the two PID controllers.

Now, if don't mind answering a couple of questions, I'd really appreciate it.

  1. For tuning the PID's should I begin should the P term with the others set to 0?
    Now that I have two PID regulators I have to admit I am a little bewildered.
  2. How do you handle the change in the angle's sign? Falling backwards/forwards? I just change the speed sign. Would you say that it is ok? (I'm still working on this one, I'm debating if I should do it individually for each motor or just use the angle's sign.
    3.I put a minimum speed of 50 steps, i doubt it's gonna be enough. How high should I go?
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <AccelStepper.h>
#include <PID_v1.h>

Adafruit_MPU6050 mpu;

int MPU_addr = 0x68;

float const_calib_X = 0;
float const_calib_Y = 0;
float const_calib_Z = 0.2;

#define dirPin_X 2
#define stepPin_X 5

#define dirPin_Y 3   //3 Y //4 Z
#define stepPin_Y 6  //6 Y //7 Z

#define enablePin 8

//PID

// PID tuning parameters for angle control
double Kp_angle = 0;
double Ki_angle = 0;
double Kd_angle = 0;

// PID tuning parameters for acceleration control
double Kp_acceleration = 0;
double Ki_acceleration = 0;
double Kd_acceleration = 0;

double input_angle = 0;
double output_angle = 0;
double setpoint_angle = 0;

double input_acceleration = 0;
double output_acceleration = 0;
double setpoint_acceleration = 0;


PID anglePID(&input_angle, &output_angle, &setpoint_angle, Kp_angle, Ki_angle, Kd_angle, DIRECT);
PID accelerationPID(&input_acceleration, &output_acceleration, &setpoint_acceleration, Kp_acceleration, Ki_acceleration, Kd_acceleration, DIRECT);

const int stepsPerRevolution = 200;
const int pulsesPerRevolution = 200;

unsigned long prevMillis = 0;
int revolutions = 0;

int led_R = 14;
int led_G = 15;
int led_B = 16;

float RateRoll, RatePitch, RateYaw;
float RateCalibrationRoll, RateCalibrationPitch, RateCalibrationYaw;
int RateCalibrationNumber;
float AccX, AccY, AccZ;
float AngleRoll, AnglePitch;
uint32_t LoopTimer;
float KalmanAngleRoll = 0, KalmanUncertaintyAngleRoll = 2 * 2;
float KalmanAnglePitch = 0, KalmanUncertaintyAnglePitch = 2 * 2;
float Kalman1DOutput[] = { 0, 0 };

int raspuns_PID = 0;

// AccelStepper instante
AccelStepper stepper1(1, stepPin_X, dirPin_X);
AccelStepper stepper2(1, stepPin_Y, dirPin_Y);

// Other constants and variables
const float alpha_angle_filter = 1;

int motorSpeed1 = 0;
int motorSpeed2 = 0;

// MPU
float filteredAngleRoll = 0.0;
float filteredAnglePitch = 0.0;


void gyro_signals() {

  double angle_correction = 1.8;

  Wire.beginTransmission(0x68);
  Wire.write(0x1A);
  Wire.write(0x05);
  Wire.endTransmission();

  Wire.beginTransmission(0x68);
  Wire.write(0x1C);
  Wire.write(0x10);
  Wire.endTransmission();

  Wire.beginTransmission(0x68);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0x68, 6);

  int16_t AccXLSB = Wire.read() << 8 | Wire.read();
  int16_t AccYLSB = Wire.read() << 8 | Wire.read();
  int16_t AccZLSB = Wire.read() << 8 | Wire.read();

  Wire.beginTransmission(0x68);
  Wire.write(0x1B);
  Wire.write(0x8);
  Wire.endTransmission();

  Wire.beginTransmission(0x68);
  Wire.write(0x43);
  Wire.endTransmission();

  Wire.requestFrom(0x68, 6);

  int16_t GyroX = Wire.read() << 8 | Wire.read();
  int16_t GyroY = Wire.read() << 8 | Wire.read();
  int16_t GyroZ = Wire.read() << 8 | Wire.read();

  RateRoll = (float)GyroX / 65.5;
  RatePitch = (float)GyroY / 65.5;
  RateYaw = (float)GyroZ / 65.5;

  AccX = (float)AccXLSB / 4096;
  AccY = (float)AccYLSB / 4096;
  AccZ = (float)AccZLSB / 4096 - const_calib_Z;

  AngleRoll = atan(AccY / sqrt(AccX * AccX + AccZ * AccZ)) * 1 / (3.142 / 180);
  AnglePitch = -atan(AccX / sqrt(AccY * AccY + AccZ * AccZ)) * 1 / (3.142 / 180);

  filteredAngleRoll = alpha_angle_filter * AngleRoll + (1 - alpha_angle_filter) * filteredAngleRoll;
  filteredAnglePitch = alpha_angle_filter * AnglePitch + (1 - alpha_angle_filter) * filteredAnglePitch;

  filteredAngleRoll = filteredAngleRoll + angle_correction;
}


void moveRobot() {

  int minSpeed = 50;

  stepper1.setSpeed(motorSpeed1 + minSpeed);
  stepper2.setSpeed(motorSpeed2 + minSpeed);
  stepper1.runSpeed();
  stepper2.runSpeed();
}

void updatePIDValues() {
  if (Serial.available() > 0) {
    String inputString = Serial.readStringUntil('\n');
    inputString.trim();

    if (inputString.startsWith("Kp_angle=")) {
      Kp_angle = inputString.substring(9).toFloat();
      anglePID.SetTunings(Kp_angle, Ki_angle, Kd_angle);
    } else if (inputString.startsWith("Ki_angle=")) {
      Ki_angle = inputString.substring(9).toFloat();
      anglePID.SetTunings(Kp_angle, Ki_angle, Kd_angle);
    } else if (inputString.startsWith("Kd_angle=")) {
      Kd_angle = inputString.substring(9).toFloat();
      anglePID.SetTunings(Kp_angle, Ki_angle, Kd_angle);
    } else if (inputString.startsWith("Kp_acceleration=")) {
      Kp_acceleration = inputString.substring(16).toFloat();
      accelerationPID.SetTunings(Kp_acceleration, Ki_acceleration, Kd_acceleration);
    } else if (inputString.startsWith("Ki_acceleration=")) {
      Ki_acceleration = inputString.substring(16).toFloat();
      accelerationPID.SetTunings(Kp_acceleration, Ki_acceleration, Kd_acceleration);
    } else if (inputString.startsWith("Kd_acceleration=")) {
      Kd_acceleration = inputString.substring(16).toFloat();
      accelerationPID.SetTunings(Kp_acceleration, Ki_acceleration, Kd_acceleration);
    }

    Serial.println("Updated PID Values:");
    Serial.print("Kp_angle: ");
    Serial.println(Kp_angle);
    Serial.print("Ki_angle: ");
    Serial.println(Ki_angle);
    Serial.print("Kd_angle: ");
    Serial.println(Kd_angle);
    Serial.print("Kp_acceleration: ");
    Serial.println(Kp_acceleration);
    Serial.print("Ki_acceleration: ");
    Serial.println(Ki_acceleration);
    Serial.print("Kd_acceleration: ");
    Serial.println(Kd_acceleration);
  }
}

void adjustMotorSpeed(double acceleration) {

  static int currentSpeed1 = 0;
  static int currentSpeed2 = 0;

  currentSpeed1 += acceleration;
  currentSpeed2 += acceleration;

  motorSpeed1 = constrain(currentSpeed1, -1000, 1000);  // Limit speeds because library only handles 1000 steps max
  motorSpeed2 = -constrain(currentSpeed2, -1000, 1000);
}

void setup() {

  pinMode(led_R, OUTPUT);
  pinMode(led_G, OUTPUT);
  pinMode(led_B, OUTPUT);

  //KALMAN+MPU START
  Serial.begin(115200);
  // while (!Serial);

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
    digitalWrite(led_R, HIGH);
  }
  Serial.println("Found a MPU6050 sensor");

  for (RateCalibrationNumber = 0; RateCalibrationNumber < 2000; RateCalibrationNumber++) {
    gyro_signals();
    RateCalibrationRoll += RateRoll;
    RateCalibrationPitch += RatePitch;
    RateCalibrationYaw += RateYaw;
    delay(1);
  }
  RateCalibrationRoll /= 2000;
  RateCalibrationPitch /= 2000;
  RateCalibrationYaw /= 2000;
  LoopTimer = micros();
  // KALMAN+MPU FINISH

  //CNC SHIELD
  pinMode(enablePin, OUTPUT);
  digitalWrite(enablePin, LOW);  //LOW=PORNIT

  //MOTORS
  pinMode(stepPin_X, OUTPUT);
  pinMode(dirPin_X, OUTPUT);
  pinMode(stepPin_Y, OUTPUT);
  pinMode(dirPin_Y, OUTPUT);

  stepper1.setMaxSpeed(1000);

  stepper2.setMaxSpeed(1000);

  pinMode(led_R, OUTPUT);
  pinMode(led_G, OUTPUT);
  pinMode(led_B, OUTPUT);

  //myPID.SetMode(AUTOMATIC);

  anglePID.SetTunings(Kp_angle, Ki_angle, Kd_angle);
  anglePID.SetMode(AUTOMATIC);  // Set PID mode to AUTOMATIC

  accelerationPID.SetTunings(Kp_acceleration, Ki_acceleration, Kd_acceleration);
  accelerationPID.SetMode(AUTOMATIC);  // Set PID mode to AUTOMATIC
}


void loop() {

  gyro_signals();

  updatePIDValues();

  // Compute angle PID output
  double angle_error = filteredAngleRoll - setpoint_angle;
  input_angle = abs(angle_error);
  anglePID.Compute();
  output_angle = constrain(output_angle, -100, 100);  // Limit output

  // Compute acceleration based on angle error
  input_acceleration = output_angle;  // Use angle PID output as acceleration input
  accelerationPID.Compute();
  output_acceleration = constrain(output_acceleration, -100, 100);  // Limit output

  // Determine direction based on angle error
  int direction1 = 1;  // Default direction for motor 1
  int direction2 = 1;  // Default direction for motor 2
  if (angle_error < 0) 
  {
    // Adjust direction for negative angle errors (e.g., need to move backwards)
    direction1 = -1;
    direction2 = 1;
  } 
      else 
      {
        direction1 = 1;
        direction2 = -1;
      }

  // Adjust motor speed based on acceleration and direction
  adjustMotorSpeed(output_acceleration * direction1);

  // Move the robot
  moveRobot();

  //DIAGNOSTICS

  //Serial.println(angle_error);
  //Serial.println(output_angle);
  //Serial.println(output_acceleration);
  //Serial.println(motorSpeed1);
  //Serial.println(motorSpeed2);
}

Thank you for your time. I believe that I have missed the point myself. I will have to rethink my code from the ground up instead of trying to add patches, this time I will focus solely on the acceleration PID's implementation.
Thank you for the help.