# How to write a PI coontroller in M-file?

1. Oct 22, 2008

### kane_lok

Hi everyone,

I am completely new to MATLAB. But I have to write a source-code in MATLAB to explain how a proportional-integral (PI) controller works. I have got my source-code, but it doesn't really work, therefore, can everyone help me out? Urgent~!

%%%---------------------------------%%%

clear all
Kp = 0.1; %%proportional gain (PI controller)
ti = 10.0; %%integral time constant (PI controller)
t=(0.0:0.01:20.0); %%time
r = 1.0.*sin(2*t*pi);
%limit(r,-0.5);
y = 0.0;
%num=[1];
%den=[2 1];
g = 1.0; %tf(num,den); %system transfer function

for i=2:length(t)
e = r - y;
%X = t-ti;
u = Kp.*(e+I);
y = u.*g;
end

figure(3),clf
subplot(4,1,1)
plot(t,r,'color','r','linewidth',3.0)
ylabel('\fontname{times}\bf{\it{r}} [pu]','fontsize',16)
hold on
grid on
subplot(4,1,2)
plot(t,e,'color','m','linewidth',3.0), hold on
ylabel('\fontname{times}\bf{\it{e}} [pu]','fontsize',16)
hold on
grid on
subplot(4,1,3)
plot(t,u,'color','r','linewidth',3.0), hold on
ylabel('\fontname{times}\bf{\it{u}} [pu]','fontsize',16)
hold on
grid on
subplot(4,1,4)
plot(t,y,'color','r','linewidth',3.0), hold on
ylabel('\fontname{times}\bf{\it{y}} [pu]','fontsize',16)
hold on
grid on

%%%------------------------------------------%%%

By the way, the problem is in the integration. Many thanks in advance.