1G = [1], [1, 10, 20]2T = close(pid(Kp, Ki, Kd), G)3t, y = step(*T)4print(poles(T[1]))5print(info(t, y, T))1G = ct.tf([1], [1, 10, 20])2C = ct.tf([20, 350, 300], [1, 0])3T = ct.feedback(C * G, 1)4print(ct.poles(T))5ct.step_info(T, T=t)1 m—0.000 m+−Kp 300 · Ki 0 · Kd 0y 0.00 m
r = 1 m00.511.5200.511.5time (s)position (m)STEP RESPONSE y(t)plant alonePPDPIDKd = 20-60-45-30-150-20-1001020real part (1/s)imaginary (rad/s)CLOSED-LOOP POLES (s-PLANE)PPDPIDKd 20
Lit wire with moving dashes: a signal is flowing along itBlocks: step input, controller (with the summing junction), plant; the script is the code cardPlots: step response and closed-loop poles, computed from the modelThe pill travelling back along the feedback wire is the measured position yA short Python script designs a controller for a mass on a spring and a damper: it stores the plant as coefficient lists, closes the loop with list arithmetic, simulates a step, finds the poles and measures overshoot and settling time. Both plots are computed from the model as the steps play: the step response of each design, and its closed-loop poles on the s-plane. Percent overshoot is how far the peak passes the final value, as a percentage of it. The 2 % settling time is when the response enters, and stays inside, a band 2 % either side of the final value.

Model and simulate

  1. Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.

A first design

Better designs

Automate and check

The Python so far

# step 1/10 · plant
# about: Mass-spring-damper G(s), Python script

# a transfer function is two lists of coefficients
# G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20
G = [1], [1, 10, 20]
print(G[0][-1] / G[1][-1])     # 0.05

step() writes T(s) in controllable canonical form (one first-order equation per power of s) and integrates it with the classical fourth-order Runge-Kutta method. With 1 ms steps the result matches python-control to every digit shown. The mass-spring-damper and the P, PD and PID gains are the worked example of the PID tutorial in the Control Tutorials for MATLAB (University of Michigan and Carnegie Mellon). Here every curve and number is recomputed in plain Python.