Advertisement
Guest User

Untitled

a guest
Feb 27th, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. -- Turbine PID Controller
  2. -- Tries to lock a turbine at a certain RPM
  3.  
  4. -- Configuration variables
  5. target_rpm = 100
  6. dt = 0.1
  7. Gp = 10
  8. Gi = 0
  9. Gd = 0
  10.  
  11. -- State variables
  12. previous_error = nil
  13. error_sum = 0
  14.  
  15. while true do
  16. -- Get turbine RPM
  17. current_rpm = peripheral.call("back", "getRotorSpeed")
  18.  
  19. -- Calculate RPM error
  20. current_error = target_rpm - current_rpm
  21.  
  22. -- Add to error_sum
  23. error_sum = error_sum + (current_error * dt)
  24.  
  25. -- Calculate proportional component
  26. proportional = Gp * current_error
  27.  
  28. -- Calculate integral component
  29. integral = Gi * error_sum
  30.  
  31. -- Calculate derivative component
  32. if previous_error ~= nil then
  33. derivative = Gd * (current_error - previous_error) / dt
  34. else
  35. derivative = 0
  36. end
  37.  
  38. -- Set turbine flow rate
  39. flow_rate = proportional + integral + derivative
  40. peripheral.call("back", "setFluidFlowRateMax", flow_rate)
  41.  
  42. -- Output controller info to left screen
  43. peripheral.call("left", "clear")
  44. peripheral.call("left", "setCursorPos", 1, 1)
  45. peripheral.call("left", "write", "tRPM: " .. math.floor(target_rpm))
  46. peripheral.call("left", "setCursorPos", 1, 2)
  47. peripheral.call("left", "write", "E: " .. current_error)
  48. peripheral.call("left", "setCursorPos", 1, 3)
  49. peripheral.call("left", "write", "P: " .. proportional)
  50. peripheral.call("left", "setCursorPos", 1, 4)
  51. peripheral.call("left", "write", "I: " .. integral)
  52. peripheral.call("left", "setCursorPos", 1, 5)
  53. peripheral.call("left", "write", "D: " .. derivative)
  54. peripheral.call("left", "setCursorPos", 1, 6)
  55. peripheral.call("left", "write", "tFR: " .. math.floor(flow_rate))
  56.  
  57. -- Adjust flow rate for actual flow rate display
  58. if flow_rate >= 2000 then
  59. flow_rate = 2000
  60. elseif flow_rate <= 0 then
  61. flow_rate = 0
  62. end
  63.  
  64. -- Output turbine info to left screen
  65. peripheral.call("left", "setCursorPos", 1, 7)
  66. peripheral.call("left", "write", "aRPM: " .. math.floor(current_rpm))
  67. peripheral.call("left", "setCursorPos", 1, 8)
  68. peripheral.call("left", "write", "aFR: " .. math.floor(flow_rate))
  69.  
  70. -- Save state for next iteration
  71. previous_error = current_error
  72.  
  73. -- Delay next iteration
  74. os.sleep(dt)
  75. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement