Skip to content

Instantly share code, notes, and snippets.

@nhtranngoc
Last active September 18, 2015 20:02
Show Gist options
  • Save nhtranngoc/9eb73e26cfebdbd8613d to your computer and use it in GitHub Desktop.
Save nhtranngoc/9eb73e26cfebdbd8613d to your computer and use it in GitHub Desktop.
function PID = discretePID (x)
%The array parameter should be in this form (kp, ki, kd, deltaT, prevErr, desired)
%x(1)-x(3) kp, ki, kd coefficients
%x(4)delta time needed to perform integration and differentiation
%x(5) previous error
%x(6) desired setpoint value
%prevErr should be a global variable
err = x(6)- x(5); %Error equals difference between desired setpoint and previous error
integral += err*x(4);
derivative = (err- x(5))/x(4);
PID = kp*err + ki*integral + kd*derivative; %PID calculation
x(5) = err; %Make previous error current error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment