Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Turbine PID Controller
- -- Tries to lock a turbine at a certain RPM
- -- Configuration variables
- target_rpm = 100
- dt = 0.1
- Gp = 10
- Gi = 0
- Gd = 0
- -- State variables
- previous_error = nil
- error_sum = 0
- while true do
- -- Get turbine RPM
- current_rpm = peripheral.call("back", "getRotorSpeed")
- -- Calculate RPM error
- current_error = target_rpm - current_rpm
- -- Add to error_sum
- error_sum = error_sum + (current_error * dt)
- -- Calculate proportional component
- proportional = Gp * current_error
- -- Calculate integral component
- integral = Gi * error_sum
- -- Calculate derivative component
- if previous_error ~= nil then
- derivative = Gd * (current_error - previous_error) / dt
- else
- derivative = 0
- end
- -- Set turbine flow rate
- flow_rate = proportional + integral + derivative
- peripheral.call("back", "setFluidFlowRateMax", flow_rate)
- -- Output controller info to left screen
- peripheral.call("left", "clear")
- peripheral.call("left", "setCursorPos", 1, 1)
- peripheral.call("left", "write", "tRPM: " .. math.floor(target_rpm))
- peripheral.call("left", "setCursorPos", 1, 2)
- peripheral.call("left", "write", "E: " .. current_error)
- peripheral.call("left", "setCursorPos", 1, 3)
- peripheral.call("left", "write", "P: " .. proportional)
- peripheral.call("left", "setCursorPos", 1, 4)
- peripheral.call("left", "write", "I: " .. integral)
- peripheral.call("left", "setCursorPos", 1, 5)
- peripheral.call("left", "write", "D: " .. derivative)
- peripheral.call("left", "setCursorPos", 1, 6)
- peripheral.call("left", "write", "tFR: " .. math.floor(flow_rate))
- -- Adjust flow rate for actual flow rate display
- if flow_rate >= 2000 then
- flow_rate = 2000
- elseif flow_rate <= 0 then
- flow_rate = 0
- end
- -- Output turbine info to left screen
- peripheral.call("left", "setCursorPos", 1, 7)
- peripheral.call("left", "write", "aRPM: " .. math.floor(current_rpm))
- peripheral.call("left", "setCursorPos", 1, 8)
- peripheral.call("left", "write", "aFR: " .. math.floor(flow_rate))
- -- Save state for next iteration
- previous_error = current_error
- -- Delay next iteration
- os.sleep(dt)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement