Advertisement
toxicfrazzles

Speed Controller

Jun 30th, 2024 (edited)
591
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.26 KB | Gaming | 0 0
  1. local sc = nil
  2. local sm = nil
  3.  
  4. local function enumerate()
  5.     local pNames = peripheral.getNames()
  6.     for index, pName in ipairs(pNames) do
  7.         local type = peripheral.getType(pName)
  8.         if not sc and type == "Create_RotationSpeedController" then
  9.             sc = peripheral.wrap(pName)
  10.         elseif not sm and type == "Create_Stressometer" then
  11.             sm = peripheral.wrap(pName)
  12.         end
  13.         if sm and sc then
  14.             return true
  15.         end
  16.     end
  17.     return false
  18. end
  19.  
  20. if not enumerate() then
  21.     error("Failed to locate speed controller and stressometer")
  22.     return
  23. end
  24.  
  25. local cap = nil
  26. local stress = nil
  27. local nextCalibration = nil
  28. local reverse = sc.getTargetSpeed() < 0
  29.  
  30. local function recalibrate()
  31.     local measurements = {}
  32.  
  33.     measurements[0] = {
  34.         speed = sc.getTargetSpeed() ,
  35.         stress = sm.getStress()
  36.     }
  37.     sc.setTargetSpeed(sc.getTargetSpeed()/2)
  38.     sleep(1)
  39.     measurements[1] = {
  40.         speed = sc.getTargetSpeed(),
  41.         stress = sm.getStress()
  42.     }
  43.     local m = (measurements[0]["stress"] - measurements[1]["stress"])/(measurements[0]["speed"]-measurements[1]["speed"])
  44.     local c = measurements[0]["stress"] - m*measurements[0]["speed"]
  45.     -- y = mx + c
  46.     -- x = (y-c)/m
  47.     local x = (sm.getStressCapacity() - c)/m
  48.     local target = 0
  49.     if reverse then
  50.         target = math.max(math.ceil(x), -256)
  51.     else
  52.         target = math.min(math.floor(x),256)
  53.     end
  54.     print("New target speed: " .. target)
  55.     sc.setTargetSpeed(target)
  56. end
  57.  
  58.  
  59. while true do
  60.     if sm.getStress() ~= stress or sm.getStressCapacity() ~= cap then
  61.         -- Something has been added to the network that uses or provides stress
  62.         print("Something changed. Due a recalibration")
  63.         nextCalibration = os.clock() + 30
  64.         stress = sm.getStress()
  65.         cap = sm.getStressCapacity()
  66.     end
  67.  
  68.     if sm.getStress() > sm.getStressCapacity() or nextCalibration and nextCalibration <= os.clock() then
  69.         -- Calibrate the stress of the system
  70.         nextCalibration = nil
  71.         print("Recalibrating...")
  72.         recalibrate()
  73.         sleep(1)
  74.        
  75.         stress = sm.getStress()
  76.         cap = sm.getStressCapacity()
  77.     else
  78.         sleep(1)
  79.     end
  80. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement