Self Balancing Robot

ironbot, here's the explanations:

  1. please let me know, what calibration here means, and why -4.5, and why added to your myangle (converted to degree? yes?)
  float calibration = -4.5; // read from a pot or something

float myangle=(angle*57.2957795130823)-90.0 + calibration;

The calibration is a fixed value that gets added to the angle, it's becouse my accelerometer is not perfectly perpendicular when the robot is in balance. That is, when the center of mass falls exacly in the line of the wheels, my accelerometer does not read 0, it reads something like 4.5. So adding -4.5 corrects the problem.
(now 4.5 is quite a big value, probably i was also messing in the code to get the robot roving around).

  1. You mean, when time is more than 6 sec. LED goes high? why? (
if ((millis()-startmillis) > 6000 )

Well, this is a strange issue: for some reason (read: due to my crappy code), the angle i read starts completely wrong when i turn on the robot. I have to wait about 5 seconds for it to reach a correct value, so i added that pause. That "if" encloses the whole motor control stuff (not just the led), so the robot is basically dead for the first 6 seconds.

  1. why P and I have pot/100, but D has pot/10?
P = (myangle * (pot1 / 100.0)); // pot/10

D = (myangle-oldAngle) * (pot2 / 10.0);

this is pure empirism: the D value is in a smaller range than P (in my specific setup), so, since the two potentiometers have the same range, i used different coefficient.
Calibrating all this stuff require a great deal of trial and error :slight_smile:

  1. why 128? why 250 and 5?
    float motors = 128.0 - (pid+(sgn(pid)*sqr(pid/18)));

// cap the value
   if (motors>250.0) motors = 250.0;
   if (motors<5.0) motors = 5.0;

My motor controller accept values between 0 and 255, where 128 is stop, 0 is full backward, 255 is full forward. So the 128 adjust to the "logical zero". The two "if" avoid the motors going to the max value (i kept 5 lower, probably not necessary, but they're quite fast anyway and i didn't wanted to push them).

  1. What is this if-block for? else is comming from having info in motorInput, but this if speakc about?
    if ((myangle > 80) || (myangle < -80))

This is the dead-man switch :slight_smile: If the robot is fallen horizontal (ie, it is at 90 degree :)), i just stop the motors and give up. Without this ifs, the wheels would keep spinning dragging the robot around.
While the robot is laying, i also stop incrementing the I value to avoid gigantic build-up of the integral component, so that when you manually turn your robot up, it can restart the balancing action.

I hope this clears some of your doubts!

Btw when will you post some pictures of your robot? :slight_smile: