nameless12242312

PID Controller

Sep 8th, 2024 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.51 KB | Gaming | 0 0
  1. PID = {}
  2. PID.__index = PID
  3.  
  4. --PID constructor for new instances
  5. function PID:newController(gain, compensation, dampening, max, min)
  6.   --input handeling
  7.   assert(type(gain) == "number","the gain value must be a number")
  8.   assert(type(compensation) == "number","the compensation value must be a number")
  9.   assert(type(dampening) == "number","the dampening value must be a number")
  10.   assert(type(max) == "number","the max value must  be a number")
  11.   assert(type(min) == "number","the min value must be a number")
  12.  
  13.   --metatable creatiion
  14.   local self_obj = setmetatable({},PID)
  15.  
  16.   --controller property assigment
  17.   self_obj.gain = gain
  18.   self_obj.compensation = compensation
  19.   self_obj.dampening = dampening
  20.   self_obj.max = max
  21.   self_obj.min = min
  22.  
  23.   --value creation for controller
  24.   self_obj.prev_err = 0
  25.   self_obj.prev_integral = 0
  26.   self_obj.prev_derivative = 0
  27.  
  28.   --object return for instantiation
  29.   return self_obj
  30. end
  31.  
  32. function PID:run(err)
  33.   --setpoint creation
  34.   local error = err
  35.  
  36.   --derivative coefficient calculation
  37.   local derivative = error - self.prev_err
  38.   self.prev_err = error
  39.  
  40.   --integral coefficient calculation
  41.   local integral = self.prev_integral + error
  42.   self.prev_integral = integral
  43.  
  44.   --output determination and clamping
  45.   local output = error * self.gain + integral * self.compensation + derivative * self.dampening
  46.   local clamped_output = math.max(self.min, math.min(self.max, output))
  47.  
  48.   --output return for system adjustment
  49.   return clamped_output
  50. end
  51.  
  52. return PID
Tags: PID Library
Advertisement
Add Comment
Please, Sign In to add comment