Advertisement
space_is_hard

LIB_PID.ks

Apr 10th, 2015
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. //=====Generic PID controller=====
  2. //~~LIB_PID.ks~~
  3. //~~Version 0.9b~~
  4.  
  5. @LAZYGLOBAL OFF.
  6.  
  7. DECLARE FUNCTION PID_Init {
  8.  
  9.     PARAMETER
  10.         Kp,     //Gain of position
  11.         Ki,     //Gain of integral
  12.         Kd.     //Gain of derivative
  13.        
  14.     LOCAL SeekP TO 0.       //Desired value for P (will get set later)
  15.     LOCAL P TO 0.           //Proportional term
  16.     LOCAL I TO 0.           //Integral term
  17.     LOCAL D TO 0.           //Derivative term
  18.     LOCAL oldT TO -1.       //Old Time; start value shows that it hasn't been calculated
  19.     LOCAL oldInput TO 0.    //Previous return value of controller
  20.    
  21.     GLOBAL 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.     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.     LOCAL Kp TO PID_Array[0].
  43.     LOCAL Ki TO PID_Array[1].
  44.     LOCAL Kd TO PID_Array[2].
  45.     LOCAL oldS TO PID_Array[3].
  46.     LOCAL oldP TO PID_Array[4].
  47.     LOCAL oldI TO PID_Array[5].
  48.     LOCAL oldD TO PID_Array[6].
  49.     LOCAL oldT TO PID_Array[7].
  50.     LOCAL oldInput TO PID_Array[8].
  51.    
  52.     LOCAL P TO seekVal - curVal.
  53.     LOCAL I TO 0.
  54.     LOCAL D TO 0.
  55.     LOCAL newInput TO oldInput.
  56.    
  57.     LOCAL T TO TIME:SECONDS.
  58.     LOCAL 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