Please see the attachment for a discrete PID controller coded in C++. The equation is highlighted in bold font. It works by keeping track of the current error (Error[2]), previous error (Error[1]) and previous previous error (Error[0]).
Sometimes, a PI controller works satisfactorily for motor speed control. You can try PI first.
- To control the speed of a motor, you need a P-I controller. A PID controller is for controlling the position of the motor axis. As this is apparently not needed, a PI is sufficient.
- For a PI controller, you basically need one zero and one pole:
1. Where there integrator takes over from the proportional, there is a zero
2. Usually (not really required), there is a low-pass pole to limit the noise pumped into the motor. (This causes power consumption and unwanted noise.)
- Typically, the P-I cross-over is a factor 2-3 below the loop bandwidth, and the lowpass pole is a factor 2-3 above the loop bandwidth. (Just rule-of-thumb)
- You need to watch the sampling frequency. You need way higher sampling than Nyquist, typically sampling frequency is 30x loop bandwidth for good operation. Note that the sampling causes time delay, and the time delay causes phase shift, and this negatively affects the loop stability.
- You should simulate loop phase margin and amplitude margin in Matlab or something like that. Please also include the effects of the digital control loop, as you cannot neglect them. (time delay causes phase shift, reduces the phase margin.)
Please note you did not ask how to obtain the speed signal. Typically this is possible with back-emf sensing (noisy, low quality), or with optical or magnetic means. In the latter case, you obtain a signal making N 1-0-1 transitions for every
revolution of the motor, and then using some filtering, you need to obtain the speed signal from that.
Could you indicate if you need explanation here too ?