# PID controller simulation

I'm trying to brush up on my understanding of controllers (PID,PD,etc). I've written a simple Matlab program that tries to simulate the
control of a spring-mass-damper system with a PID controller (you can adjust gains, system properties, etc). Can anyone familiar in this area do a quick check of my program to see if they spot any obvious errors?
%PID simulation------------------- %mass in kg m=1; %spring constant in n/m k; %dampening coefficient d=.5;
%starting point x1=1; %initial velocity v=0; %time step dt=.01; %matrix index i=1;
%gains gainpP; gainiP; gaind;
%desired position x_desired=2; %integrated error, initial value=0 is=0;
x=x1; t=0; while t<20 XM(i)=x; s=x_desired-x; is=is+s*dt; SM(i)=s; if i==1 spast=s; end %ds=slope/derivative of error ds=(s-spast)/dt; %force applied by the controller f_controller=gainp*s+gaind*ds+gaini*is; VM(i)=v; T(i)=t; %total force with damper and spring included f=-k*x-v*d+f_controller; FM(i)=f; a=f/m; AM(i)=a; x=x+v*dt+a*dt^2/2; v=v+a*dt; t=t+dt; i=i+1; %spast=previous 's' value for next ds calculation spast=s; end
plot(T,XM,'r')
<% if( /^image/.test(type) ){ %>
<% } %>
<%-name%>
dave.harper wrote:

Well, first off, dt2 in "x=x+v*dt+a*dt2/2" is not defined, do you mean dt^2? That is just from trying to run it. if you want to get really fancy you can do your integration with a more sophisticated method.
What's the purpose of the simulation?
-Matt
<% if( /^image/.test(type) ){ %>
<% } %>
<%-name%>
Matthew Douglas Rogge wrote:

Thanks for the reply... Looking back, I'm pretty sure I typed "x=x+v*dt+a*dt^2/2", not dt2. The point of the program is mainly just to give myself a tool I can play around with and better understand controllers...
Did you try to run it with dt^2?
Thanks again, Dave
<% if( /^image/.test(type) ){ %>
<% } %>
<%-name%>
dave.harper wrote:

Yeah, it works with dt^2. What toolboxes do you have? There is a function in the control toolbox called sisotool that allows you to take a plant and add controller poles and zeros to the root locus interactively. This allows you to watch the root locus, frequency response, and/or closed loop step response change on the fly. PID is a good start, but depending on your needs, you may need to branch out to a wider variety of controllers to get an understanding of whats really going on.
-Matt
<% if( /^image/.test(type) ){ %>
<% } %>
<%-name%>
I didn't check it line by line - but the usual gotcha is forgetting the sign of the rate term is to oppose! the correction, the integral and proportional is to aid the correction.
Better to dump the PID in favor of a fuzzy - so much more intuitive, I hear....
Brian W
wrote:

<% if( /^image/.test(type) ){ %>
<% } %>
<%-name%>

i've got to disargree on that if you can do it with a PID, you should do it with a PID fuzzy-logic has a very week response time and you don't know anything about the step/line-response, integration of errors and so on