PD of PID in a balancing robot

michael_x:
In your initial post code, there is some stuff after that, which I don't understand:

...

analogWrite(RPWM, -output);
 }  // probably not good enough, but understood up to here  ;)
 
 output = -1 * output;
   if(output >= 0)
 {
   digitalWrite(RDIRA, HIGH);
   digitalWrite(RDIRB, LOW);
   analogWrite(RPWM, output);
 }
 else
 {
   digitalWrite(RDIRA, LOW);
   digitalWrite(RDIRB, HIGH);
   analogWrite(RPWM, -output);
 }

}//if(!(angle>30 || angle < -30))
 else
 {
   analogWrite(LPWM, 0);
   analogWrite(RPWM, 0);
 }




I assume *output* should represent the speed you want your robot to move. It does not need to be exactly proportional, but you should work on that a bit, too. 
- What's the minimum/maximum speed your bot can do ? For smooth and easy contol, motor should react immediately with slow speed. Max speed should rather tell you when to give up. 
- What's the dynamic behavior of your balancing rod when it falls ? angle / angular velocity over time ?
- I think you don't need sin/cos even (5.7° = 0.1 * R is sufficient around your "set point") but a bit of math won't hurt.
- Did you consider that the more your sensor has left the 0° position, the more moving the motor will accelerate it ?

oh, sorry, I just got that you are pointing this:

  output = -1 * output;

well, I just changed motors and swapped the left/right wires of motors and one of them started to turn not in the right direction, instead of changing in hardware, I added that line to just turn the output sign to the opposite one, which in turn effects on the 'if' decision and I got the motor turning again on the right direction.

I set 255 to get max. speed and it is claimed by the seller that this motor turns 300rpm, but I did not pass any motor identification process to give a reliable data of the speed.

dynamic behavior - I'm not sure if I got what you mean by that, when it falls: it takes some 10 deg and only by then the motor reaction happens, which is late, and robot starts to fall, and motors get to turn so fast, until it falls completely and motors stop :frowning:

I think you don't need sin/cos even - also didn't get you! sorry!

the more moving the motor will accelerate it ? - no, I don't feel that, but I'd submit a behavioral video, so you all who are kindly helping see it, that is better than me describing it, yet with my English which is noisy :slight_smile: