Programming
For a robot to balance well it needs at least 2 sensors to help it know when it is falling. Those sensors are an accelerometer and a gyroscope. The accelerometer measures the forces acting on the robot including the movement of the robot. The accelerometer is very noisy, meaning it does not give very precise data, and is affected by the movement of the robot; however, the accelerometer always knows which way is up. The gyroscope measures the angular velocity of the robot. It is very precise but, it only measures the angular velocity and not pitch and roll. At first I thought that I would only need one of these sensors to have the robot balance; however, neither one is very good alone. The gyroscope cannot be used to make a reliable balancing robot because it does not know when it is level. The angular velocity could be measured over a short period of time and be converted into a distance traveled and all of the distances be added up over time but, the gyroscope would start to drift and the longer the program would run the more the tiny errors in the calculation would add up and eventually the robot would fall off. The accelerometer would work for a longer period of time but it would be very imprecise and the robot would quickly fall off the ball. To make a good balancing robot the values from the accelerometer and gyroscope have to be combined.
The best way to combine the data is by using a Kalman filter. I have tried other kinds of filters and have seen that this one gives the most accurate results. The Kalman filter takes the gyroscope and accelerometer values and calculates the amount of trust each one deserves. It can change the amount of trust while running and gives a much more accurate reading that the complementary filter. Once the pitch and roll are calculated by the Kalman filter the robot takes the arctangent of the two values to find the driving angle.
The robot also needs to know how fast to go. If it is near the center of the ball it should move slower than when it is about to fall off. The best way to calculate the speed is to use a PID controller. PID stands for Proportional Integral Derivative. It basically lets the robot act in proportion to the distance from the center while keeping it from going too far and allowing the robot to react quickly to any sudden changes.
The driving angle and the driving speed are given to the robot which can calculate how fast each wheel should turn to achieve the desired direction and speed. The motor controller program turns the speed of the wheels into electrical signals that are given to the motor controller breakout boards to turn the motor.