Lab 05: Two-Wheeled Balancing Robot (Pitch Loop)
Overview
A hobby-class two-wheeled robot balances by driving its wheels under its centre of mass. Near upright the pitch dynamics are an inverted pendulum with one right-half-plane pole, so P control cannot balance it, the Nyquist plot must encircle $-1$ once counter-clockwise, the gain margin becomes a range with a lower and an upper limit, and the phase margin sets the largest loop delay the firmware may have. The logs show a robot that balances through two pushes, and the same robot tipping over after a firmware change added delay.

The balancing robot R1 and its PD pitch loop.
The system
The body (mass $m_b$, centre of mass at height $l$ above the axle, inertia $I_b$ about the centre of mass) sits on two wheels (total mass $m_w$, radius $r$) driven by a torque $\tau$. The wheels roll without slip and are free, since this lab treats the pitch loop only and has no wheel position loop. In the code $I_b$ is a fixed number, so changing $m_b$ in dict(M.ROBOT_A, m_b=...) adds or removes mass at the centre of mass, and changing $l$ moves the body without changing its own inertia.
| quantity | robot R1 (demos) | robot R2 (homework) | basis |
|---|---|---|---|
| body mass $m_b$ | 1.0 kg | taller and heavier than R1 | representative hobby robot |
| axle to centre of mass $l$ | 0.10 m | ||
| body inertia $I_b$ (box 0.22 m × 0.06 m) | 4.3 × 10⁻³ kg m² | ||
| wheels $m_w$, $r$ | 0.10 kg, 34 mm | larger wheels | |
| torque limit (both motors) | ±0.5 N m | ±1.2 N m | |
| unstable pole $p$, input gain $b_0$ | 13.2 rad/s, 631 rad/s²/(N m) | identify from the logs | from the parameters |
| control loop | 200 Hz, PD with derivative filter $T_f$ = 5 ms, one sample of sensor and computation delay plus the zero-order hold ($T_d = 1.5\,T_s$ = 7.5 ms), 8-bit PWM, 45° tilt cutoff | same structure | firmware |
| IMU | gyro noise 0.1 °/s, bias 0.4 °/s, accelerometer tilt noise 0.3 °, complementary filter $\alpha$ = 0.98 | same | MEMS IMU |
| firmware gains in the logs | $K_p$ = 1.379 N m/rad, $K_d$ = 0.0585 N m s/rad | in the log files | hand-tuned |
Linearizing the wheel and body equations about upright and eliminating the wheel position gives the pitch transfer function
$$ \begin{aligned}G(s) &= \frac{\Theta(s)}{T(s)} = \frac{b_0}{s^2 - p^2},\\p^2 &= \frac{a b g}{a c - b^2}, \quad b_0 = \frac{a + b/r}{a c - b^2},\end{aligned} $$with $a = m_w + I_w/r^2 + m_b$, $b = m_b l$, $c = I_b + m_b l^2$ and $I_w = m_w r^2/2$. The angle $\theta$ is positive when the body leans backward and $\tau$ is positive when it drives the wheels forward; then $b_0 > 0$ and the usual negative feedback $\tau = -C(s)\,\theta$ balances the robot. The logs were simulated with the nonlinear equations ($\sin\theta$, RK4 integration), the IMU model, the torque limit and the PWM resolution; they are not measurements from a real robot.
| step | course tool | lecture |
|---|---|---|
| inverted-pendulum model, right-half-plane pole (demo 1) | modeling, transfer function | L3, L4 |
| $p$ from the drop test (demo 1) | exponential modes, least squares | L5, L6 |
| $b_0$ from the closed-loop log with dither (demo 1) | equation-error least squares | L3 |
| P control fails (demo 1) | root locus of $b_0 K/(s^2 - p^2)$ | L13 |
| stabilizing PD range (demo 1) | Routh-Hurwitz | L10, L11 |
| PD gains for $\zeta = 0.7$, $\omega_n = 2p$ (demo 2) | root locus, angle and magnitude conditions, extra filter pole | L13-L17 |
| Bode plot of an unstable plant (demo 2) | same magnitude as $b_0/(s+p)^2$, different phase | L22 (Part 3) |
| stability with $P = 1$ (demo 3) | Nyquist criterion, one counter-clockwise encirclement | L23, L24 |
| lower and upper gain margin, phase margin (demo 3) | margins on the Nyquist and Bode plots | L26 |
| largest loop delay (demo 3) | delay margin $\mathrm{PM}/\omega_c$, checked by simulation and with the tip-over log | L26 |
Demo 1: an unstable plant identified from two logs
An unstable plant cannot be step-tested open loop, so the model comes from two other experiments. In the drop test the motors are off and the body is released near upright. Then $\ddot\theta = p^2\theta$, and released from rest the angle grows as $A e^{pt} + B e^{-pt}$. The fit adds a constant $c$ for the small angle offset that the gyro bias leaves in the complementary filter:
$$ \theta(t) = A e^{pt} + B e^{-pt} + c . $$For a trial value of $p$ this expression is linear in $A$, $B$ and $c$, so each trial is a small least-squares problem, and a one-dimensional search keeps the $p$ with the smallest residual. Only the part with $|\theta| < 10^\circ$ is used, where $\sin\theta \approx \theta$. The fit gives $p = 12.93$ rad/s against the true 13.19 rad/s (an error of $-2.0$ %). A straight line through $\ln|\theta|$ gives 12.81 rad/s because it ignores the $e^{-pt}$ term. The growing mode $e^{pt}$ doubles every $\ln 2/p = 54$ ms, which sets the time scale the controller has to beat.

Drop test with the motors off: the fit $Ae^{pt} + Be^{-pt} + c$ on $|\theta| < 10^\circ$.
The input gain $b_0$ comes from the balancing log. Integrating $\ddot\theta = p^2\theta + b_0\tau(t - T_d)$ over windows that exclude the two pushes gives a linear least-squares problem in $(p^2, b_0)$ that needs no differentiation of noisy data:
$$ \omega_{gyro}(t) - \omega_{gyro}(t_0) = p^2 \int_{t_0}^{t} \theta\,dt + b_0 \int_{t_0}^{t} \tau\,dt + c\,(t - t_0), $$where $c$ absorbs the small angle offset caused by the gyro bias and the torque is the logged command shifted by the one-sample loop delay. In closed loop the torque $\tau \approx -K_p\theta - K_d\dot\theta$ is almost a copy of $\theta$, so the two regressors are nearly collinear. The firmware therefore adds a small PRBS dither to the torque during this test, which brings the correlation of the two regressors down to $-0.68$. The fit gives $p = 13.71$ rad/s (+3.9 %) and $b_0 = 633$ rad/s²/(N m) (+0.4 %), so the identified model used in demos 2 and 3 is $G(s) = 633/(s^2 - 187.8)$.

The balancing log with pushes at 3 s and 6.5 s and the dithered torque command (simulated log, 200 Hz).
Demos 1 and 2: why P control fails, the Routh range, and PD design on the root locus
With $C = K$ the characteristic equation is $s^2 + (K b_0 - p^2) = 0$. The poles at $\pm p$ meet at the origin when $K = p^2/b_0 = 0.297$ N m/rad and then move along the imaginary axis, so no gain puts both poles in the open left half plane. The best P control can do is an undamped oscillation, and any delay tips it over.

Root locus with P control: the poles never enter the open left half plane.
The firmware PD is $C(s) = K_p + K_d s/(T_f s + 1)$, and the closed-loop characteristic polynomial is
$$ T_f s^3 + s^2 + \big(b_0(K_d + K_p T_f) - p^2 T_f\big)s + (b_0 K_p - p^2) = 0 . $$The first column of the Routh array is $T_f$, $1$, $b_0 K_d$ and $b_0 K_p - p^2$, so the loop is stable if and only if $K_p > p^2/b_0 = 0.297$ N m/rad and $K_d > 0$. The derivative term is what makes balancing possible. This model has no upper gain limit because the loop delay is not in it yet; demo 3 adds the delay.
Demo 2 places the closed-loop poles at $\zeta = 0.7$ (about 5 % overshoot) and $\omega_n = 2p$, so that the loop is clearly faster than the fall, whose time constant is $1/p$. With the ideal PD $C(s) = K_d(s + z)$, $z = K_p/K_d$, matching $s^2 + b_0 K_d s + (b_0 K_p - p^2)$ to $s^2 + 2\zeta\omega_n s + \omega_n^2$ gives
$$ K_d = \frac{2\zeta\omega_n}{b_0}, \qquad K_p = \frac{\omega_n^2 + p^2}{b_0}, $$that is $K_p = 1.483$ N m/rad and $K_d = 0.0606$ N m s/rad with the zero at $-24.5$ rad/s, close to the firmware gains in the logs. On the root locus of $K_d b_0 (s + z)/(s^2 - p^2)$ the branches leave the real axis between $+p$ and $-p$, circle around the zero and pass through the target poles $-19.2 \pm j19.6$ rad/s, where the angle condition holds. The derivative filter adds a pole at $-1/T_f = -200$ rad/s. It pulls the far branch away to $-150.7$ rad/s and shifts the dominant pair to $-24.6 \pm j19.7$ rad/s, which raises its damping ratio from 0.70 to 0.78. The Bode plot shows why the plant’s instability is invisible in the magnitude: $|j\omega - p| = |j\omega + p|$, so $G(s) = b_0/(s^2 - p^2)$ and the stable $G_s(s) = b_0/(s + p)^2$ have identical magnitudes, while $\angle G = -180^\circ$ at every frequency and $\angle G_s$ goes from $0^\circ$ to $-180^\circ$.
The interactive version takes $K_p$ and $K_d$, draws the root locus with the zero $-K_p/K_d$ fixed and $K_d$ varied (or the P-control locus when $K_d = 0$), checks the Routh conditions, and redraws the loop gain on the Bode plot.
Interactive: PD control on the root locus and the Routh range
The button loads Python (Pyodide with numpy, scipy, matplotlib and python-control, about 40 MB on the first visit, cached afterwards) into this page; after that, changing a parameter re-runs the computation and redraws the figures. Until then the figures and numbers below are the output of the original demo script with the default parameters.
Routh: stable iff Kp > p^2/b0 = 0.297 N m/rad and Kd > 0 Kp = 0.237, Kd = 0.0500: max Re(pole) = +1.15 rad/s Kp = 1.380, Kd = 0.0000: max Re(pole) = +0.00 rad/s Kp = 1.380, Kd = 0.0585: max Re(pole) = -23.54 rad/s identified model: G(s) = 633 / (s^2 - 187.8), poles at +/- 13.71 rad/s target poles s = -19.2 +/- j19.6 rad/s PD gains: Kp = 1.483 N m/rad, Kd = 0.0606 N m s/rad, zero at s = -24.5 rad/s (firmware gains in the log: Kp = 1.379, Kd = 0.0585) angle condition at s_d: -180.0 deg; magnitude condition gives Kd = 0.0606 closed-loop poles with the filter pole (Tf = 0.005 s): [-150.7 +0.j -24.6+19.7j -24.6-19.7j] |G(j0)| = |Gs(j0)| = 3.37 rad/(N m) = 10.6 dB; phase G = -180 deg, Gs = 0 deg at all w -> 0


Python output
(appears after the first live run)
Show code
Loading the source...Demo 3: Nyquist with an unstable open loop, two gain margins, and the delay limit
The loop is evaluated as the firmware runs it:
$$ \begin{aligned}L(j\omega) &= C(e^{j\omega T_s})\,G(j\omega)\,e^{-j\omega T_d},\\T_d &= n T_s + \tfrac{T_s}{2},\end{aligned} $$with $n$ samples of sensor and computation delay and half a sample for the zero-order hold. The firmware derivative is a filtered backward difference,
$$ \begin{aligned}C(z) &= K_p + K_d \frac{(1 - a)(1 - z^{-1})}{T_s (1 - a z^{-1})},\\a &= \frac{T_f}{T_f + T_s},\end{aligned} $$which at 200 Hz costs several degrees of phase at crossover compared with $K_p + K_d s/(T_f s + 1)$, so it is evaluated exactly. The open loop has one right-half-plane pole ($P = 1$). With $Z = N + P$ and $N$ the number of clockwise encirclements of $-1$, a stable closed loop ($Z = 0$) needs $N = -1$, which is one counter-clockwise encirclement. The plot starts at $L(0) = -K_p b_0/p^2$, on the negative real axis to the left of $-1$; the phase lead of the D term carries it through the lower half plane for $\omega > 0$, and the delay winds it into the origin. With the firmware gains and one sample of delay ($T_d$ = 7.5 ms) the count is one counter-clockwise encirclement and the loop is stable.
The real-axis crossings of $L(j\omega)$ at $-1/\mathrm{GM}$ mark where a gain change would move a crossing across $-1$, and here there are two. At $\omega = 0$ the crossing lies at $-K_p b_0/p^2 = -4.65$: if the gain drops below $p^2/(K_p b_0) = 0.215$ of its value ($-13.3$ dB), the plot no longer encircles $-1$, which is the Routh limit $K_p > p^2/b_0$ again. The second crossing, made by the delay at 97 rad/s, gives the upper limit: the gain may rise by a factor of 2.73 (+8.7 dB). The exact sampled-data closed loop confirms both limits: at 0.95 and 1.05 times each margin the largest closed-loop pole magnitude $|z|$ moves across 1. The phase margin is $\mathrm{PM} = 29.1^\circ$ at $\omega_c = 41.8$ rad/s (6.7 Hz). A pure delay keeps $|L|$ and rotates the phase by $-\omega T$, so at crossover the loop absorbs
$$ \begin{aligned}T_{extra} &= \frac{\mathrm{PM}\,[\mathrm{rad}]}{\omega_c} = 12.1\ \mathrm{ms},\\T_{max} &= T_d + T_{extra} = 19.6\ \mathrm{ms}\end{aligned} $$before the plot touches $-1$. In whole samples of the 200 Hz loop the robot is stable with 3 samples ($T_d$ = 17.5 ms, largest $|z|$ = 0.9866) and unstable with 4 ($T_d$ = 22.5 ms, largest $|z|$ = 1.0140), and at the limit it oscillates near $\omega_c$, with a period of about 150 ms.
The interactive version takes $K_p$, $K_d$ and the loop delay in samples. It counts the encirclements, checks the result with the exact closed-loop poles of the sampled loop, reports the lower and upper gain margins, the phase margin and the delay margin, and simulates a torque tap on the linear model and a release from 2° on the nonlinear robot with the same delay. Changed settings are drawn against the firmware loop (grey).
Interactive: Nyquist plot, gain and phase margins, and the loop delay
The button loads Python (Pyodide with numpy, scipy, matplotlib and python-control, about 40 MB on the first visit, cached afterwards) into this page; after that, changing a parameter re-runs the computation and redraws the figures. Until then the figures and numbers below are the output of the original demo script with the default parameters.
G(s) = 633/(s^2 - 187.8); firmware PD Kp = 1.379, Kd = 0.0585, Tf = 0.005 s; loop delay Td = 7.5 ms net counter-clockwise encirclements of -1: 1 (P = 1 -> need 1) lower gain margin (w = 0): GM = 0.215 = -13.3 dB -> gain may drop to 22 % before it falls upper gain margin (w = 97 rad/s): GM = 2.73 = +8.7 dB phase margin PM = 29.1 deg at crossover wc = 41.8 rad/s (6.7 Hz) gain x 0.204: max |closed-loop pole z| = 1.006 -> UNSTABLE gain x 0.226: max |closed-loop pole z| = 0.991 -> stable gain x 2.595: max |closed-loop pole z| = 0.990 -> stable gain x 2.869: max |closed-loop pole z| = 1.007 -> UNSTABLE delay margin T_extra = 12.1 ms -> total loop delay T_max = 19.6 ms in whole samples of the 200 Hz loop: stable up to 3 samples (Td = 17.5 ms), unstable at 4 (Td = 22.5 ms) exact sampled loop with 3 samples: max |z| = 0.9866 exact sampled loop with 4 samples: max |z| = 1.0140 at the limit the loop oscillates at about wc = 41.8 rad/s, period 150 ms tip-over log: delay 6 samples, Td = 32.5 ms > T_max = 19.6 ms; fell at t = 0.83 s model with this delay: PM = -31 deg, CCW encirclements = -1 (need 1) -> unstable pole s = 8.5 +/- j32.8 rad/s growing oscillation in the log: about 33 rad/s (zero crossings, before saturation dominates)


Python output
(appears after the first live run)
Show code
Loading the source...In the simulations of the demo, the linear model with 3 samples of delay rings for about a second and settles, while with 4 samples the oscillation grows. On the nonlinear robot the torque limit turns the growing oscillation at 4 samples into a limit cycle of about ±14°, and with 6 samples the robot falls.
The last figure is the logged tip-over of firmware v2, in which blocking telemetry made the loop delay 6 samples, a total loop delay of $T_d$ = 32.5 ms, well above $T_{max}$ = 19.6 ms. The robot fell after 0.83 s. With this delay the model gives $\mathrm{PM} = -31^\circ$ and a net encirclement count of $-1$, so the closed loop has an unstable pair at $s = 8.5 \pm j32.8$ rad/s. The zero crossings of the logged angle give a growing oscillation at about 33 rad/s before the torque saturates, which agrees with the predicted pole. This figure is shown as computed by the lab script.

The logged tip-over with a 6-sample loop delay (simulated log).
Homework: will robot R2 stay up with the new telemetry? (100 points)
Robot R2 is a taller and heavier robot balanced by its team with a hand-tuned PD loop at 200 Hz. The team wants to add Bluetooth telemetry, and a first firmware version with blocking telemetry tipped over. The homework starts from three simulated logs of R2 (a drop test, a balancing run with two pushes and torque dither, and the tip-over) and asks whether, and with how much telemetry delay, the robot can stay up. The full problem statements are in homework.md, and the starter script hw_starter.py is in the lab folder of the lab materials on GitHub; the logs are in its data/ folder. Clone the repository, or download it as a zip file.
- Unstable pole from the drop test (10 points; L3, L10)
- Input gain from the closed-loop log (15 points; L3, L10)
- P fails, PD works (10 points; L10, L11, L13)
- PD design on the root locus (15 points; L13-L17)
- Bode plot of an unstable plant (10 points; L22 Part 3)
- Nyquist, margins and the delay limit (20 points; L23, L24, L26)
- The tip-over (10 points; L24, L26)
- Engineering judgement (10 points)