PID help

I am aware that PID threads are pretty common here on CD, and I have read most of them, unfortunately I am stuck in a college dorm and lack the ability to give this code a whirl.


This is my periodic tasks. I am using a loop to check where our lifter mechanism is located (via THIS encoder, I have the right numbers for it to return inches), I am wondering if I have all I need here to get a basic PID running.

Here is how I plan to tune it (provided the code is fine):
My first step in tuning would be to set the P to about .25 (small enough?) I would have I and D at zero. After I reached a point of instability I would back off on Proportional a little and add in some Integral. I only plan on this being a PI controller, as I don’t believe I will need any Derivative. Does this sound like the right tuning method?

Thanks for any help!

Things to consider:
The comment says the loop runs at 20 hertz, but it is actually programmed to go 200 hz.

The loop is reading the encoders and limit switches directly, but is only setting a variable for the output. Things will get wonky if the other loop doesn’t update the motor very often or in phase with this loop. It won’t matter if the controller is primarily proportional, but this will mess with integral and derivative terms. I’d recommend updating the motor in this loop and doing the necessary logic to get rid of the other location.

The fact that the limit switches modify the encoder or substitute a value could cause issues if the switches and encoder aren’t well calibrated. It seems like this discontinuity would be confusing when leaving the limits to travel in between. I am by no means an expert, but it seems like it may be preferable to have limit transitions read the encoder and modify the setpoint.

Greg McKaskle

Here is a slightly modified version of the previous code, It has some fixes to it (my bad on the timing of the loop :yikes: ) the lift motor (linAct) is now updated in the loop to prevent anything from getting out of phase.


Could you elaborate why resetting the encoder to zero when the lift is physically at its low point is bad. I don’t quite understand. As far as the upper limit switch I can make it a last resort thing.

Thanks for the help.

The comment about the limit switch using its own value for the encoder was more specific to the upper one.

If the elevator is at the upper limit and sends 29 to the PID, then the motor lowers it just below the upper switch, it would be confusing if that encoder value were 30 or 27. So I guess I was just trying to help with imagining things to test and either prevent, or make the code tolerant.

I’m assuming the encoder is relative and needs to be reset at some point. Doing it each time is fine provided it isn’t a false signal.

Greg McKaskle