Archive for January, 2013

PID Controller in MATLAB

I’ve had several people ask me for a MATLAB implementation of a PID controller. I took my previous PID controller post and ported it to MATLAB. Because MATLAB is not designed for software like this, I made a single PID instance code set. In other words, the following code only represents one controller.

Here is the code for the update function (you must place it in a file named pid_update.m)

function pid_update(curr_error, dt)
    global windupGuard;
    global proportional_gain;
    global integral_gain;
    global derivative_gain;
    global prev_error;
    global int_error;
    global control;

    % integration
    int_error = int_error + (curr_error * dt);

    % integration windup guarding
    if (int_error < -(windupGuard))
         int_error = -(windupGuard);
    elseif (int_error > windupGuard)
         int_error = windupGuard;
    end

    % differentiation
    diff = ((curr_error - prev_error) / dt);

    % scaling
    p_term = (proportional_gain * curr_error);
    i_term = (integral_gain     * int_error);
    d_term = (derivative_gain   * diff);

    % summation of terms
    control = p_term + i_term + d_term;

    % save current error as previous error for next iteration
    prev_error = curr_error;

Here is some VERY basic code just used to call the update function once.

global windupGuard;
global proportional_gain;
global integral_gain;
global derivative_gain;
global prev_error;
global int_error;
global control;

% set these as needed
windupGuard = 10.0;
proportional_gain = 4.0;
integral_gain = 5.0;
derivative_gain = 3.0;

% this is the zeroize function
prev_error = 0.0;
int_error = 0.0;

% call update function
pid_update(19, 1.0)

Here’s a question for those of you here reading this: Why on earth are you using MATLAB for a PID controller?

Advertisements