Skip to content

Instantly share code, notes, and snippets.

@zesterer
Created March 4, 2018 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zesterer/ae829f6192f7366911f62e5b81b69d54 to your computer and use it in GitHub Desktop.
Save zesterer/ae829f6192f7366911f62e5b81b69d54 to your computer and use it in GitHub Desktop.
Kerbal Space Program Hovering PID Controller
import krpc, time, math
conn = krpc.connect(name = "PID Hover")
vessel = conn.space_center.active_vessel
# Find the craft height (altitude from command module and bottom of craft are different)
bbox = vessel.bounding_box(vessel.reference_frame)
HEIGHT = max(abs(bbox[0][1]), abs(bbox[1][1]))
print("Now controlling '" + vessel.name + "'")
# We need this for later
surf_frame = vessel.orbit.body.reference_frame
# Some program constants
RATE = 0.1
TGT_ALT = 100 - HEIGHT / 2
# PID constants
K_C = 0.25
K_P = -0.03
K_I = 0.01
K_D = -5.5
# The integral and differential component data
prev_err = []
prev_alt = vessel.flight().surface_altitude
vessel.auto_pilot.engage()
timer = 0
while True:
# Ensure we're pointing upwards
vessel.auto_pilot.target_direction = (1, 0, 0)
alt = vessel.flight().surface_altitude
# Calculate the PID components
integral = sum(prev_err) * RATE
proportion = alt - TGT_ALT
differential = (alt - prev_alt) * RATE
# Sum the components and set the craft throttle
throttle = K_C + K_P * proportion + K_I * integral + K_D * differential
vessel.control.throttle = throttle
# Keep pushing / pulling the integral buffer
prev_err.append(alt - TGT_ALT)
if len(prev_err) > 1 / RATE:
prev_err = prev_err[1:]
prev_alt = alt
time.sleep(RATE)
# Print only occasionally
if timer == 10:
print("Throttle = " + str(throttle) + "(P = " + str(K_P * proportion) + ", I = " + str(K_I * integral) + ", D = " + str(K_D * differential) + ")")
timer = 0
else:
timer += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment