2013-08-06 33 views
0

我试图实现一个简单的脚本来执行一个巡航控制应用程序的PI控制,但我发现一些问题与积分部分。这里是我的代码:在matlab中手动实现的PI控制算法

function [] = PI_cruisecontrol() 
clc; close all; 
t0 = 0; tfinal = 50; dt = 0.001;    % time parameters 
r = 10;           % reference of 10 m/s 
m = 1000;          % mass 
b = 50;           % friction coeff. (depends on v) 
yp = zeros(tfinal/dt,1); t = yp;    % initialize speed and time array 
Ki = 40;          % integrarl constant 
Kp = 800;          % proportional constant 
int = 0;          % itinialize int error 
% CONTROL LOOP (Forward-Euler integrator is used to solve the ODE) 
for i=t0+2:tfinal/dt 
    err = r-yp(i-1);       % update error 
    int = int+err;       % integral term 
    u  = (Kp*err)+(Ki*int*dt);    % action of control 
    yp(i) = yp(i-1)+((-b*yp(i)/m) + (u/m))*dt; % solve ode for speed 
    t(i) = t(i)+dt*i;       % log the time     
end 
% Results 
figure(1) 
plot(t,yp) 
title ('Step Response') 
xlabel('Time (seconds)') 
ylabel('Amplitud') 
axis([0 20 0 12]) 
hold on 
reference = ones(tfinal/dt,1)*10; 
plot(t,reference,':') 
end 

这是应该的,使用MATLAB predefinided功能:

function [] = PI_cruisecontrol2() 
m = 1000; 
b = 50; 
r = 10; 
s = tf('s'); 
P_cruise = 1/(m*s + b); 
Kp = 800; 
Ki = 40; 
C = pid(Kp,Ki); 
T = feedback(C*P_cruise,1); 
t = 0:0.1:20; 
step(r*T,t) 
axis([0 20 0 12]) 
end 

什么我在我的代码做错了什么? 谢谢!

回答

1

我设法解决这个问题,使用float变量而不是数组。此外,我添加了衍生术语(虽然对于这个第一个订单问题是没有必要的) 这里我离开了代码:

function [] = aFortran_PI() 
clc; close all; 
r = 10;       % reference of 10 m/s 
m = 1000;      % mass 
b = 50;       % friction coeff. (depends on v) 
yp = 0;       % init response  
Kp = 800;      % proportional constant 
Ki = 40;      % proportional constant 
Kd = 0;       % derivative term is not necessary in this problem 
previous_error = 0; 
integral = 0; 
dt = 0.001; 
% CONTROL LOOP 
for i=1:20000 
    error = r-yp;      % update error 
    integral  = integral + error*dt;  % integral term 
    derivative = (error-previous_error)/dt; % derivative term 
    u = Kp*error+Ki*integral+Kd*derivative; % action of control 
    yp = yp+(-b*yp/m + u/m)*dt % solve ode for velocity 

end 
end