MATLAB Answers

# How to control a valve with PID

34 views (last 30 days)
Gustav Ngemasong Chafac on 10 Jul 2018
Commented: Aquatris on 16 Aug 2018
In order to maintain a constant pressure in a system, I need to control a valve opening. If the pressure is more than the required value, increase the valve opening and vice versa. How can I control this using a PID controller so that the pressure remains at the required value and not overshoot or undershoot?
##### 5 CommentsShowHide 4 older comments
Aquatris on 16 Aug 2018
errorC is cumulative error and yes you will start with errorC = 0 and then each step you add the new error. This serves as a simple integral.
errorP is the previous error and it is used to find the derivative of the error signal, or the rate of change of the error.
The idea stays the same whether it is real life or simulation.
Here is a simple mass-spring example;
% Simple mass spring example
% actuator applies force to the mass
% sensor sense the position of the mass
% control drives the mass to desired position
% /| _____
% /| k | |
% /|---/\/\/\/--| m |
% /| |_____|
% /|
%
% mass-spring parameters
k = 10; % [N/m]
m = 2; % [kg]
% system equation of motion
% xd = Ax + Bu
% y = Cx + Du
A = [0 1;
-k/m 0];
B = [0
1/m];
C = [1 0];
D = 0;
sys = ss(A,B,C,D); % marginally stable open loop
% input is force, output is position
% controller
Kp = 10; Ki = 8; Kd = 5; % parameters to be tuned
s = tf('s');
K = Kp + Ki/s + Kd*s;
% closed loop system
sysCL = feedback(sys*K,1);
% simulate response of the system
step(sysCL)
Or if you are more of an equation type of guy;
dt = 1e-3; % time step size, the smaller the number is,
% the more realistic the outcome is due to integration
t = 0:dt:15;% time vector
x(1) = 0; % initial position
xd(1) = 0; % initial velocity
xdd(1) = 0; % initial acceleration
u(1) = 0; % initial control input
eC = 0; % errorC, cumulative error for integral control
eP = 0; % errorP, previous error
desiredX = 1; % desired position of the mass
% can be time dependent function instead of a constant
for i = 1:length(t)-1
e = desiredX - x(i); % calculate error
eC = eC+e;
u(i) = Kp*e + Ki*eC*dt + Kd*(e-eP)/dt; % control law right here
xdd(i) = 1/m*(-k*x(i) + u(i)); % accel = totalForce / mass
xd(i+1) = xd(i)+xdd(i)*dt; % get velocity via integration of accel
x(i+1) = x(i)+xd(i)*dt; % get position via integration of vel
eP = e; % store current error as previous error
% for the next iteration of the loop
end
% plot the system response
plot(t,x)

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!