Advertisement
space_is_hard

LIB_PID

Apr 5th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. //=====Generic PID controller=====
  2. //~~LIB_PID.ks~~
  3. //~~Version 0.1~~
  4.  
  5. @LAZYGLOBAL off.
  6.  
  7. DECLARE FUNCTION PID_Init {
  8.  
  9.     DECLARE PARAMETER
  10.         Kp,     //Gain of position
  11.         Ki,     //Gain of integral
  12.         Kd.     //Gain of derivative
  13.        
  14.     DECLARE SeekP TO 0.     //Desired value for P (will get set later)
  15.     DECLARE P TO 0.         //Proportional term
  16.     DECLARE I TO 0.         //Integral term
  17.     DECLARE D TO 0.         //Derivative term
  18.     DECLARE oldT TO -1.     //Old Time; start value shows that it hasn't been calculated
  19.     DECLARE oldInput TO 0//Previous return value of controller
  20.    
  21.     DECLARE PID_Array TO LIST().
  22.     PID_Array:ADD(Kp).          //[0]
  23.     PID_Array:ADD(Ki).          //[1]
  24.     PID_Array:ADD(Kd).          //[2]
  25.     PID_Array:ADD(SeekP).       //[3]
  26.     PID_Array:ADD(P).           //[4]
  27.     PID_Array:ADD(I).           //[5]
  28.     PID_Array:ADD(D).           //[6]
  29.     PID_Array:ADD(oldT).        //[7]
  30.     PID_Array:ADD(oldInput).    //[8]
  31.    
  32.     RETURN PID_Array.
  33.    
  34. }. //FUNCTION PID_Init
  35.  
  36. DECLARE FUNCTION PID_Seek {
  37.     DECLARE PARAMETER
  38.         PID_Array,      //Array built with PID_Init; updated with each call to PID_Seek
  39.         seekVal,        //Desired value
  40.         curVal.         //Current value
  41.    
  42.     DECLARE Kp TO PID_Array[0].
  43.     DECLARE Ki TO PID_Array[1].
  44.     DECLARE Kd TO PID_Array[2].
  45.     DECLARE oldS TO PID_Array[3].
  46.     DECLARE oldP TO PID_Array[4].
  47.     DECLARE oldI TO PID_Array[5].
  48.     DECLARE oldD TO PID_Array[6].
  49.     DECLARE oldT TO PID_Array[7].
  50.     DECLARE oldInput TO PID_Array[8].
  51.    
  52.     DECLARE P TO seekVal - curVal.
  53.     DECLARE I TO 0.
  54.     DECLARE D TO 0.
  55.     DECLARE newInput TO oldInput.
  56.    
  57.     DECLARE T TO TIME:SECONDS.
  58.     DECLARE dT TO T - oldT.
  59.    
  60.     IF oldT < 0 {
  61.         //Nothing
  62.     } ELSE {
  63.         IF dT = 0 {
  64.             SET newInput TO oldInput.
  65.         } ELSE {
  66.             SET D TO (P - oldP) / dT.
  67.             SET I TO (oldI + P) * dT.
  68.             SET newInput TO Kp * P + Ki * I + Kd * D.
  69.         }.
  70.     }.
  71.    
  72.     SET PID_Array[3] TO seekVal.
  73.     SET PID_Array[4] TO P.
  74.     SET PID_Array[5] TO I.
  75.     SET PID_Array[6] TO D.
  76.     SET PID_Array[7] TO T.
  77.     SET PID_Array[8] TO newInput.
  78.    
  79.     RETURN newInput.
  80.    
  81. }. //FUNCTION PID_Seek
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement