I'm trying to build a 2-wheel balancing robot, but it is way to jerky to balance properly.

Hardware: ESP32, MPU6050, L298N, two motors and a 9v battery.

I've tried playing around with the PID settings (a lot) and I'm at a point where I believe that there is something else causing problems.

I think that the issue is coming from the angle calculation. I've followed numerous different methods posted online, and I've settled on using the Adafruit MPU6050 library, but the output is 1) really noisy and 2) ranges between roughly -60° to 60°, which I thought wouldn't be a problem, but I'm not sure anymore.

float get_angle() {
  previousTime = currentTime;
  currentTime = millis();
  elapsedTime = (currentTime - previousTime) / 1000;

  mpu.getEvent(&a, &g, &temp);
  float angle = (atan(-1 * a.acceleration.x / sqrt(pow(a.acceleration.y, 2) + pow(a.acceleration.z, 2))) * 180 / PI);
  return angle;

The main issue with other solutions I've looked at online is that they always seem to have a significant amount of drift, despite their output being much smoother. A possible root cause could be a difference in compute speed between an ESP and an Arduino, so the error correction might be off, but I don't know how to fix it / if it is the actual issue.

For example, I was able to get decent data out of this example (with some minor modifications), but the value drifts a significant amount for me.

What is the best way to read in and process accelerator and gyroscope data to get an angle in degrees, without drifting and significant noise, when using an ESP32?

(There is also an issue where disconnecting the ESP from USB makes the entire system act as if it's reactions are delayed, but that is not my primary concern at the moment)

  • 1
    please add a clear, answerable question to your post
    – jsotola
    Sep 21 at 5:59
  • What are the data types of the variables used in the code excerpt you posted? How often is get_angle() called? Sep 21 at 8:04
  • Re “the value drifts a significant amount”: did you keep the IMU completely still during the calibration procedure? Sep 21 at 8:18
  • I confess, I stopped reading after "and a 9v battery". Almost any project w/motors & a processor will require a power source capable of providing more current than a 9v battery.
    – st2000
    Sep 21 at 13:02
  • @EdgarBonet a g and temp are declared as sensor_event_t, all the timing variables are floats. The get_angle() function is called every iteration of the loop() function. I tried running it multiple times per loop and taking the average to smooth the value out, which works, but it runs too slow for the pid controller to react in time. I have been keeping it still during calibration.
    – Zelkins
    Sep 21 at 18:27


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy