Launch into Orbit

This tutorial launches a two-stage rocket into a 150km circular orbit. The program assumes you are using this craft file.

The program is available in a variety of languages:

C#, C++, Java, Lua, Python

The following code connects to the server, gets the active vessel, sets up a bunch of streams to get flight telemetry then prepares the rocket for launch.

 1using System;
 2using System.Collections.Generic;
 3using System.Net;
 4using KRPC.Client;
 5using KRPC.Client.Services.SpaceCenter;
 6
 7class LaunchIntoOrbit
 8{
 9    public static void Main ()
10    {
11        var conn = new Connection ("Launch into orbit");
12        var vessel = conn.SpaceCenter ().ActiveVessel;
13
14        float turnStartAltitude = 250;
15        float turnEndAltitude = 45000;
16        float targetAltitude = 150000;
17
18        // Set up streams for telemetry
19        var ut = conn.AddStream (() => conn.SpaceCenter ().UT);
20        var flight = vessel.Flight ();
21        var altitude = conn.AddStream (() => flight.MeanAltitude);
22        var apoapsis = conn.AddStream (() => vessel.Orbit.ApoapsisAltitude);
23        var stage2Resources =
24            vessel.ResourcesInDecoupleStage (stage: 2, cumulative: false);
25        var srbFuel = conn.AddStream(() => stage2Resources.Amount("SolidFuel"));
26
27        // Pre-launch setup
28        vessel.Control.SAS = false;
29        vessel.Control.RCS = false;
30        vessel.Control.Throttle = 1;
31
32        // Countdown...
33        Console.WriteLine ("3...");
34        System.Threading.Thread.Sleep (1000);
35        Console.WriteLine ("2...");
36        System.Threading.Thread.Sleep (1000);
37        Console.WriteLine ("1...");
38        System.Threading.Thread.Sleep (1000);
39        Console.WriteLine ("Launch!");

The next part of the program launches the rocket. The main loop continuously updates the auto-pilot heading to gradually pitch the rocket towards the horizon. It also monitors the amount of solid fuel remaining in the boosters, separating them when they run dry. The loop exits when the rockets apoapsis is close to the target apoapsis.

41        // Activate the first stage
42        vessel.Control.ActivateNextStage ();
43        vessel.AutoPilot.Engage ();
44        vessel.AutoPilot.TargetPitchAndHeading (90, 90);
45
46        // Main ascent loop
47        bool srbsSeparated = false;
48        double turnAngle = 0;
49        while (true) {
50
51            // Gravity turn
52            if (altitude.Get () > turnStartAltitude &&
53                altitude.Get () < turnEndAltitude) {
54                double frac = (altitude.Get () - turnStartAltitude)
55                              / (turnEndAltitude - turnStartAltitude);
56                double newTurnAngle = frac * 90.0;
57                if (Math.Abs (newTurnAngle - turnAngle) > 0.5) {
58                    turnAngle = newTurnAngle;
59                    vessel.AutoPilot.TargetPitchAndHeading (
60                        (float)(90 - turnAngle), 90);
61                }
62            }
63
64            // Separate SRBs when finished
65            if (!srbsSeparated) {
66                if (srbFuel.Get () < 0.1) {
67                    vessel.Control.ActivateNextStage ();
68                    srbsSeparated = true;
69                    Console.WriteLine ("SRBs separated");
70                }
71            }
72
73            // Decrease throttle when approaching target apoapsis
74            if (apoapsis.Get () > targetAltitude * 0.9) {
75                Console.WriteLine ("Approaching target apoapsis");
76                break;
77            }
78        }

Next, the program fine tunes the apoapsis, using 10% thrust, then waits until the rocket has left Kerbin’s atmosphere.

80        // Disable engines when target apoapsis is reached
81        vessel.Control.Throttle = 0.25f;
82        while (apoapsis.Get () < targetAltitude) {
83        }
84        Console.WriteLine ("Target apoapsis reached");
85        vessel.Control.Throttle = 0;
86
87        // Wait until out of atmosphere
88        Console.WriteLine ("Coasting out of atmosphere");
89        while (altitude.Get () < 70500) {
90        }

It is now time to plan the circularization burn. First, we calculate the delta-v required to circularize the orbit using the vis-viva equation. We then calculate the burn time needed to achieve this delta-v, using the Tsiolkovsky rocket equation.

 92        // Plan circularization burn (using vis-viva equation)
 93        Console.WriteLine ("Planning circularization burn");
 94        double mu = vessel.Orbit.Body.GravitationalParameter;
 95        double r = vessel.Orbit.Apoapsis;
 96        double a1 = vessel.Orbit.SemiMajorAxis;
 97        double a2 = r;
 98        double v1 = Math.Sqrt (mu * ((2.0 / r) - (1.0 / a1)));
 99        double v2 = Math.Sqrt (mu * ((2.0 / r) - (1.0 / a2)));
100        double deltaV = v2 - v1;
101        var node = vessel.Control.AddNode (
102            ut.Get () + vessel.Orbit.TimeToApoapsis, prograde: (float)deltaV);
103
104        // Calculate burn time (using rocket equation)
105        double F = vessel.AvailableThrust;
106        double Isp = vessel.SpecificImpulse * 9.82;
107        double m0 = vessel.Mass;
108        double m1 = m0 / Math.Exp (deltaV / Isp);
109        double flowRate = F / Isp;
110        double burnTime = (m0 - m1) / flowRate;

Next, we need to rotate the craft and wait until the circularization burn. We orientate the ship along the y-axis of the maneuver node’s reference frame (i.e. in the direction of the burn) then time warp to 5 seconds before the burn.

112        // Orientate ship
113        Console.WriteLine ("Orientating ship for circularization burn");
114        vessel.AutoPilot.ReferenceFrame = node.ReferenceFrame;
115        vessel.AutoPilot.TargetDirection = Tuple.Create (0.0, 1.0, 0.0);
116        vessel.AutoPilot.Wait ();
117
118        // Wait until burn
119        Console.WriteLine ("Waiting until circularization burn");
120        double burnUT = ut.Get () + vessel.Orbit.TimeToApoapsis - (burnTime / 2.0);
121        double leadTime = 5;
122        conn.SpaceCenter ().WarpTo (burnUT - leadTime);

This next part executes the burn. It sets maximum throttle, then throttles down to 5% approximately a tenth of a second before the predicted end of the burn. It then monitors the remaining delta-v until it flips around to point retrograde (at which point the node has been executed).

124        // Execute burn
125        Console.WriteLine ("Ready to execute burn");
126        var timeToApoapsis = conn.AddStream (() => vessel.Orbit.TimeToApoapsis);
127        while (timeToApoapsis.Get () - (burnTime / 2.0) > 0) {
128        }
129        Console.WriteLine ("Executing burn");
130        vessel.Control.Throttle = 1;
131        System.Threading.Thread.Sleep ((int)((burnTime - 0.1) * 1000));
132        Console.WriteLine ("Fine tuning");
133        vessel.Control.Throttle = 0.05f;
134        var remainingBurn = conn.AddStream (
135            () => node.RemainingBurnVector (node.ReferenceFrame));
136        while (remainingBurn.Get ().Item1 > 0) {
137        }
138        vessel.Control.Throttle = 0;
139        node.Remove ();
140
141        Console.WriteLine ("Launch complete");
142        conn.Dispose();
143    }
144}

The rocket should now be in a circular 150km orbit above Kerbin.