21. Problem systems.

function setup(){
  t=0;
  tmax = 200;
  demand=60;
  ambient=20;
  tank=ambient;
  pipe= Array(100);
  for(i=0;i<101;i++){pipe[i]=ambient;}
  tout=ambient;
  a=0.1;   // Time constant about ten seconds
  b=7;     // Will give 70 degrees temperature rise for u=1.
  dt = .1;
  integral=0;
  tint=20;
  fbgain=document.getElementById("fb").value/100; 
  tint=document.getElementById("fi").value*100;
  ScaleWindow(-5,-5,tmax,110);
  DrawAxes(0,0,tmax,100);
  Label('Proportional+Integral',150,85);
  Colour("black");
  Label('Output temperature',150,80);
  Colour("blue");
  Label('Target temperature',150,75);
  Colour("magenta");
  Label('Integral %',150,70);
  Colour("red");
  Label('Power %',150,65);
  Colour("black");
  t = 0;
  i=0;
  MoveTo(t,tank);
  loop();
}

function loop(){
  integral=integral+(demand-tout)*dt/tint;
  if(integral>1){integral=1;}
  if(integral<0){integral=0;}  
  u=(demand-tout)*fbgain+integral;
  if(u>1){u=1;}
  if(u<0){u=0;}
  tank=tank+(a*(ambient-tank)+b*u)*dt;
  tout=pipe[i];
  pipe[i]=tank;
  i=i+1;
  if(i>99){i=0;}

  t = t + dt;
  Colour("blue");
  Spot(t, demand);
  Colour("magenta");
  Spot(t, integral*100);
  Colour("red");
  Spot(t, u*100);
  Colour("black");
  Spot(t, tout);
  if (t<tmax){setTimeout('loop()',10);}
}