How do I perform PID controller from error by using matlab script?

8 views (last 30 days)
I want to change the PID that is shown in this figure to matlab script
I am tring to use
PID=Kp*ev + Ki * integral(ev)+ Kd * diff(ev);
But the term "Ki * integral(ev)" gives an error
  1 Comment
Sam Chak
Sam Chak on 15 Mar 2024
I asked the MATLAB Assistant the following question: "How can I simulate a system with the equation x'' + x' + x = u, where the error-based PID controller u is defined as u = Kp*e + Ki*∫ e dt + Kd*de/dt, and the values of Kp, Ki, and Kd are 24.75, 25, and 24.7525 respectively? I would like to set the setpoint to 1 and run the simulation for 1 second using ode45."
Unfortunately, the simulation is giving multiple error messages. Additionally, I have presented the expected output responses from the pid() and feedback() commands.
%% ----- Expected result ------
Gp = tf(1, [1 1 1]); % Plant
kp = 24.75;
ki = 25;
kd = 24.7525;
Gc = pid(kp, ki, kd) % PID controller
Gc = 1 Kp + Ki * --- + Kd * s s with Kp = 24.8, Ki = 25, Kd = 24.8 Continuous-time PID controller in parallel form.
Gcl = feedback(Gc*Gp, 1); % closed-loop
step(Gcl, 1), grid on
Code generated by MATLAB Assistant in AI Chat Playground
% Define the PID controller gains
kp = 24.75;
ki = 25;
kd = 24.7525;
% Define the desired setpoint
setpoint = 1;
% Define the error signal
error = @(t, x) setpoint - x(1);
% Create a function that calculates the control signal
controlSignal = @(t, x) kp*error(t, x) + ki*trapz(t, error(t, x)) + kd*gradient(error(t, x))/gradient(t);
% Define the system dynamics
systemDynamics = @(t, x) [x(2); - 1*x(2) - 1*x(1) + controlSignal(t, x)];
% Define the simulation time span
tspan = [0 1];
% Define the initial conditions
x0 = [0; 0];
% Simulate the system using ode45
[t, x] = ode45(systemDynamics, tspan, x0);
Error using matlab.internal.math.getdimarg
Dimension argument must be a positive integer scalar within indexing range.

Error in trapz>getDimArg (line 90)
dim = matlab.internal.math.getdimarg(dim);

Error in trapz (line 44)
dim = min(ndims(y)+1, getDimArg(dim));

Error in solution>@(t,x)kp*error(t,x)+ki*trapz(t,error(t,x))+kd*gradient(error(t,x))/gradient(t) (line 21)
controlSignal = @(t, x) kp*error(t, x) + ki*trapz(t, error(t, x)) + kd*gradient(error(t, x))/gradient(t);

Error in solution>@(t,x)[x(2);-1*x(2)-1*x(1)+controlSignal(t,x)] (line 24)
systemDynamics = @(t, x) [x(2); - 1*x(2) - 1*x(1) + controlSignal(t, x)];

Error in ode45 (line 293)
f3 = ode(t3, y3);
% Plot the response
plot(t, x(:, 1)), grid on
xlabel('Time');
ylabel('Output');
title('Response');

Sign in to comment.

Answers (0)

Tags

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!