PID controller and transfer function in C++

Sik picture Sik · Apr 25, 2018 · Viewed 12k times · Source

I have a PID controller working in simulink, but I want to pass it to C++ code. I found how to make a PID with code, something like this:

error = input - refeed;
iError += error * sampleTime;
dError = (error - lastError)/ sampleTime;
//PID Function
output = Kp * error + Ki * iError + Kd * dError;
refeed = output;
lastError = error;

But, that's the only clear thing I got in my research.

I need to know what's the next step, I have the transfer function discretized but I'm not sure about what should I do with the "z" parameters, the times, ...

Is it possible to pass manually a PID controller to C++? How?

Answer

Junho Park picture Junho Park · Apr 11, 2019

For the digital control systems, you need to sample the data and execute the controller at every sampling time. z-transform converts the continuous system to the discrete system.
For exampl, if your sampling time is '1', you can express a simple time-series model as below,

y(t) = a1*u(t-1) + a2*u(t-2)
--> y(t) = a1*z^-1*u(t) + a2*z^-2*u(t)
--> y(t) = A(z)u(t), where A(z) = a1*z^-1 + a2*z^-2
a1, a2 = FIR coefficients

However, this time-shift operator 'z^-1' does not appear in your code. It is implicitly expressed with your sampling-time and FOR or DO loop depending on the language that you are using. Please see the python code for velocity form of PID controller. Velocity form is a little bit easier to implement because you don't worry about the additional logic for the anti-reset windup.

for i in range(1, ns):  #ns = simulation time
    # PID Velocity form
    e[i] = sp[i] - pv[i]
    P[i] = Kc * (e[i] - e[i-1])
    I[i] = Kc*delta_t/tauI * (e[i])
    D[i] = Kc*tauD/delta_t * (pv[i] - 2*(pv[i-1]) + pv[i-2])
    op[i] = op[i-1] + P[i] + I[i] + D[i]
    if op[i] < oplo or op[i] > ophi:
        # clip output
        op[i] = max(oplo,min(ophi,op[i]))

You can also find an example of a PID controller using a GEKKO package in the following link.

https://apmonitor.com/wiki/index.php/Main/GekkoPythonOptimization