Ball Balancing

Video of Computer Screen Running Ball Balance (2019)


I have always wanted to do some sort of balancing mechanism. Some years ago I was given a RobotGeek Snapper Arduino Robotic Arm for Christmas. The arm is controlled by an Arduino, but RobotGeek provides example code which has Processing code on the PC communicating with the Arduino which then moves the robotic arm. While studying this code I also found this Processing tutorial which shows how to track a color from a web cam. (I cannot say enough about the many great tutorials on the YouTube channel "The Coding Train"!) So I kludged all this code along with some PID examples from Parallex Inc. to balance a golf ball in a wooden track, which I made for the robotic arm.

There are plenty of other examples on the web of balancing ball videos (this video has a good explanation on understanding and setting PID coefficients in the second half of the video.) That would not have stopped me from making my own, but I had not found any using a camera as the sensor (in early 2019). But here is a hefty one I found while writing this page.

I added a constant offset to the PID methodology, this is where the wooden track is level, either this is an enhancement, or I am using PID incorrectly. The project might further be enhanced to provide compensation for starting resistance verses rolling resistance.

The Arduino code

The Arduino code must be started before the Processing code.

What The Arduino code does

The Arduino code listing

The Processing code

The Processing code must be started after the Arduino code. The user then clicks the middle mouse button over the target. Then the user clicks the right mouse button over the ball. The user can then adjust the PID coefficients use the sliders.

What The Processing code does

  • In setup()
    • Open a GUI.
    • Create slider controls for changing the PID coefficients (upper right).
    • Open serial port to Arduino to receive command requests (RP) and send back commands (HD,M,xxx).
    • Prepare the camera.
  • In draw()
    • Keep a constant command frame rate, otherwise PID coefficients change with code execution time.
    • Draw a camera image to the display window.
    • Check if mouse is setting the color/location of the target (yellow).
    • Check if mouse is setting the color/location of the ball (purple).
    • Find the target.
    • Find the ball.
    • Calculate the error and new wrist location using PID.
    • Wait for a command request then send the command packet.
    • Plot the history of Error (red), PID Result (blue) and Frame Rate (green).

    The Processing code listing