MotorLab simulates a geared permanent-magnet DC servo in real time and closes a digital PID loop around it —
the same architecture found in robot joints, 3-D printer axes, gimbals and electric actuators.
1 · Plant model
Electrical and mechanical dynamics are integrated with 4th-order Runge–Kutta at 20 kHz (all values referred to the output shaft):
L·di/dt = V − R·i − K·ω
J·dω/dt = K·i − b·ω − τc·tanh(ω/ωs) − τload
dθ/dt = ω
Defaults: R = 2 Ω, L = 5 mH, K = 0.5 N·m/A, J = 0.05 kg·m², b = 0.01 N·m·s. The mechanical time constant is
τm = J·R/(K² + R·b) ≈ 0.37 s and the electrical one L/R = 2.5 ms. The supply voltage saturates the drive.
2 · Digital PID
u[k] = Kp·e[k] + I[k] + D[k]
I[k] = I[k−1] + Ki·Ts·e[k] (frozen while saturated)
D[k] = a·D[k−1] − (1−a)·Kd·(y[k]−y[k−1])/Ts, a = Tf/(Tf+Ts)
- Derivative on measurement avoids the “derivative kick” on setpoint steps.
- First-order derivative filter (cut-off fc, Tf = 1/2πfc) limits noise amplification.
- Conditional-integration anti-windup stops the integrator from charging while the output is clipped.
- The encoder quantises the angle (counts/rev) and optional Gaussian noise is added — try 64 CPR with a large Kd.
3 · Step metrics
Every setpoint step is captured and normalised: rise time (10→90 %), percentage overshoot, 2 % settling time,
steady-state error and IAE = ∫|e|dt. Pin a response to compare tunings side by side.
4 · Loop analysis
The loop transfer function uses the linearised plant and the continuous PID, with the zero-order-hold approximated as a half-sample delay:
P(s) = K / ( s · [(J s + b)(L s + R) + K²] ) (position)
C(s) = Kp + Ki/s + Kd·s/(Tf·s + 1)
L(jω) = C(jω)·P(jω)·e^(−jω·Ts/2)
Phase margin, gain margin, crossover frequency and closed-loop bandwidth are read from the Bode plot; the
Poles tab solves 1 + C·P·Padé(s) = 0 with a scaled Durand–Kerner root finder.
5 · Auto-tuning
- Relay feedback (Åström–Hägglund): a relay ±d forces a limit cycle; its amplitude a and period Tu give the ultimate gain Ku = 4d/(π√(a²−ε²)). Classic rules (Ziegler–Nichols, Tyreus–Luyben, …) map (Ku, Tu) to PID gains.
- Bump test + model-based design: an open-loop voltage step identifies a first-order-plus-dead-time model (28 % / 63 % method). Position loops get a PD+I pole placement (ζ = 0.8); velocity loops get SIMC PI tuning (Skogestad).
Things to try
- Apply a load torque with a PD controller (Ki = 0): note the steady-state error, then add integral action.
- Drop the sample rate to 50 Hz and watch the phase margin shrink.
- Turn anti-windup off and command a large step — the integrator winds up and overshoot explodes.
- Quadruple the inertia and re-run the auto-tuner.