1gas = 50 # %, set once2# never reads the speed1error = 100 - speed2gas = 50 + 5 * error3gas = min(max(gas, 0), 100)100 km/h0–100 %—+25 %100.0 km/hflaterror +0.0 km/h100.0 km/h
goal 100 km/h← hill from 20 s020406080100120708090100time (seconds)km/hSPEED ON THE HILLopen loopclosed loopgoal 100 km/htrailer on from 0 s020406080100120708090100time (seconds)km/hSPEED WITH THE TRAILERopen loopclosed loop
Lit wire with moving dashes: a signal or force is flowing along itBlocks: set speed, engine, car, speedometer, hill and trailer; the controller is the code cardPlots: speed over time on the hill and with the trailer, open loop and closed loop, computed from the modelThe pill travelling back to the controller is the speedometer reading: feedbackA cruise-control loop: the set speed, the controller (a short Python rule), the engine (actuator), the car (plant) and the speedometer (sensor). A hill is a disturbance; a trailer is a change in the car itself. The plots below are simulated from the car model as the steps play: open loop loses about 20 km/h in both cases, feedback only about 2. The hill is modelled as a steady pull worth 10 % of throttle. A real slope pulls back with the car's weight times the sine of its angle; turning that into throttle depends on the engine, so this lesson keeps it as one number.

The car

  1. Cruise control holds a car at a speed the driver picks, here 100 km/h. In the words of “Parts of a loop”: the car is the plant, the engine is the actuator and the speedometer is the sensor.

Disturbances

Coping with change

What is happening

# step 1/10 · cruise
# about: Set speed 100, Engine (actuator), Car (plant), Speedometer (sensor)

goal (setpoint)   100 km/h
plant             the car (output: speed)
actuator          engine, throttle 0 to 100 %
sensor            speedometer

The car's speed follows the throttle with
a time constant of 20 s: about how long
it takes to get two-thirds of the way.

The car is a simple model with illustrative numbers: in steady state it goes 2 km/h for every % of throttle (1.6 with the trailer), with a 20-second time constant. Every curve and number in the figure is computed from that model. The Python on each step is plain Python 3 with the math module. It updates the throttle every 0.05 s and moves the car forward with the exact solution of its equation between updates, just as the figure does.