Ok, a PID loop adds the three terms (Proportional, Integral, and Deravitive) to get a drive percentage. 0 percent, don't supply any power, 100 percent, supply full power. (there are certainly other conventions, but this is the one I chose for this post).
Proportional Term:
This is the easiest to understand. You drive the motor proportionally to the distance from the current state to the set point (desired state). The formula for this term is:
Code:
P = ERROR * GAIN = (SET_STATE - CURRENT_STATE) * GAIN
You have to play a little to adjust your gain.
Integral Term:
This is a little harder to understand, perhaps. You are going to take the error, and integrate it over time, and then scale it by some gain (possibly different from the gain above). I won't get too deep into theory, but this term helps to adjust for long term, unexpected impedences to the process you are controlling.
The formula is:
Code:
I = INTEGRAL(ERROR * dt) * GAIN
Derivitive Term:
This helps correct unexpected disturbances that only effect the process momentarily. It's formula is:
Code:
D = d[ERROR] * GAIN
Where d[ERROR] is change in error, or (LAST_ERROR - CURRENT_ERROR).
Then the total drive would be P+I+D
Sorry I don't have time to explain more thouroughly. Interestingly enough, I wrote a paper on this this summer, so I could talk a lot about it

But I'll be brief, and I recomend doing some research online or at a library.
Stephen
PS. Sorry, that is only theory above. I'll work on getting some sample code later, but I'm in class right now, so that's all I have time for.