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?

Thanks in advance! Dave

%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

plot(T,XM,'r')

Thanks in advance! Dave

%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; endplot(T,XM,'r')