top:
  print("\n\rStarting...")
  wait(10000)
  print("\n\r")
  pressuredefault=(10)*58   '(PSI) running pressure in 0.1psi
  updaterate=(10000)*28  '(ms) time between updates
  faultcurrent=(10)*10  '(amps) absolute maximum battery current in 0.1 Amps
  rolloff=(6)*10        '(amps) where to start limiting pressure in 0.1 Amps
  maxcurrent=(8)*10     '(amps) maximum battery current at which pressure = 0 psi, in 0.1 Amps
  rollscale=100/(maxcurrent-rolloff)
  counter=updaterate  'this allows a quick update after pause
  pressureset=pressuredefault
  setcommand(_VAR,1,pressureset/58)
forever:
  counter++
  bamp=getvalue(_BATAMPS,1)
  if bamp > faultcurrent Then goto faulthalt  'over absolute maximum, shut it down
  bamperror=(maxcurrent-bamp)*rollscale   'what is the error
  pressureset=getvalue(_VAR,1)*58
  if (pressureset < 0) or (pressureset > 870) then pressureset=pressuredefault
  if bamperror <0 then                 'it is over maximum then 
    pcommand=0                         'set to 0 since pump could run backwards
  elseif bamperror < 100 then          'is it at limiting threshold
     pcommand=(pressureset*bamperror)/100 'by how much to limit pressure
  else 
     pcommand=pressureset              'no limiting necessary
  end if
  setcommand(_GO,1,pcommand)           'set the new pressure
  if counter < updaterate then goto forever  'time to send an update
  pwr=getvalue(_MOTPWR,1)
  pressure=getvalue(_ANAINC,1)
  pressure=(pressure*100)/580
  pcommand=(pcommand*100)/580
  print(pcommand," , ",pressure," , ",bamp," , ",pwr/10,"\n\r")
  counter=0
  goto forever
faulthalt:                  'hard fault, estop and send error
  SetCommand(_ESTOP,1)
  setcommand(_GO,1,0)          
  print("Over Current ",bamp,"\n\r")
  terminate
  
