The segway tries to get the angle down to 0°. If the angle is positive, the segway brakes or accelerates backwards. If it's negative the segway accelerates forward.

But which signal get the motors? This is exactly the task of the pid-Controller.

The **p**roportional-part: The angle should be 0°. So the greater the angle, the higher the speed of the motors.

Mathematically you can write:

angle_error = angle_should - angle_is

p-Motor-value = k_p * angle_error

The **i**ntegral-part: When the current angle isn't zero, the Controller tries to get the segway horizontally again. But this approach shouldn't be slow and the smaller the angle-values, the slower the changes. Therefore the Controller allows a faster approach with the disadvantage, that the movement doesn't stop at 0° and goes a bit to the other side. This behaviour is guaranteed by the integral-part. All the angles are added (integrated) and this integral over time should be Zero. So if the angle is f.e. positive for a while, the Controller tries to get the seqway into the negative area. This guaranteeds faster approaches...

Mathematically you can write:

error_sum_new = error_sum_old + error

i-motor-value = k_i * (error_sum_new)

error_sum_old = error_sum_new

The **d**erivative-part: Not just the current angle is important but also the changes of the angle. Let me explain: If the angle is f.e. 10° and it doesn't Change a lot, the Motors don't need to correct this shift very fast. But if the angle is 10° and it changes very fast (high derivative), than the motors have to correct this also very fast.

Mathematically you can write:

d-motor-value = k_d * angular Speed

Finally you get: motor-value = p-motor-value + i-motor-value + d-motor-value