tmladek:
Hi!

I want to control a motor with PWM, reading a rotary encoder to get speed, and I thought PID would be a good fit. However, I'm confused about a couple things, mostly regarding the proportional term.

First off, when the speed gets higher than the setpoint, the error gets negative, right? When then multiplied by the proportional constant, the output variable also is negative, but the PWM duty cycle is only 0-100% (or 0-255).

No, often when you control a motor the PID output is a signed value, positive for forward, negative for
backwards - then you can do full control by position or speed, forwards or backwards or stationary.

Even for one-direction speed control you forget the integrating term which "remembers" the normal
steady state output from the loop, so the the proportional error term is merely correcting a difference from
this normal output. The integrating term slowly adapts to changes in operating point and nulls out the
error to zero in steady state.

However the complexity arises when the system as a whole is not linear (a varying load, or using
slow-decay mode in the motor controller), then you often have to turn down the PID gains for
stability and lose control performance. Great though the I term is it reduces stability, so is always
rather a compromise.

There's no substitute for actually playing with a PID loop and tuning it and seeing what these things
mean in practice - a lot of the theory assumes linear system with constant load, but real systems are
messier. More advanced control strategies can help, but they are more complex.

And lastly don't forget that feed-forward is often very useful, not just feed-back - this could be as
simple as adding a fixed offset onto the output of the PID loop to compensate for the normal load.