---
title: "Capstone: balance an inverted pendulum"
heading: Why a stick balanced upright falls exponentially and why short sticks are harder to balance, catching it by accelerating the cart with angle feedback, why angle feedback alone lets the cart run away, and a full-state controller designed by pole placement and tested on the nonlinear pendulum
eyebrow: D3 · Lesson 10 · Capstone
xp: 80
---

::: hook
Balancing a broomstick on your palm is the classic control problem: the stick is unstable, so doing nothing means it falls, and you catch it by moving your hand under it. A Segway, a rocket on its exhaust and a walking robot all solve the same problem. It brings together every idea in this course: an unstable pole, feedback that moves it, damping to stop the swinging, the state-space view that keeps the cart from wandering off, and a simulation to check that a design based on a linear model works on the real, nonlinear system.
:::

::: play
- A pendulum of length L standing on a cart, near upright. Without control its angle obeys $\ddot\theta = (g/L)\theta$, so it falls exponentially at rate $\sqrt{g/L}$.
- The cart accelerates by $a = k_p\theta + k_d\dot\theta$, moving under the pendulum as it leans. The arrows show how angle and angular velocity evolve from each point.
- With $k_p$ below g (9.81 m/s² per radian), no amount of damping saves it. Above g, the upright position becomes a stable spiral or node.
:::

```sim plot
view: flow
x: th = -0.5..0.5
y: w = -3..3
slider: L = 0.2..2 step 0.05 = 0.5
slider: P = 0..40 step 0.5 = 20
slider: D = 0..10 step 0.1 = 4
dx: w
dy: (9.81*th - (P*th + D*w))/L
start: 0.3, 0
start: -0.2, 2
start: 0.05, -2.5
heads: on
readout: falling rate with no control, 1/s = sqrt(9.81/L) | digits: 3
readout: restoring stiffness (P − g)/L, must be positive = (P - 9.81)/L | digits: 3
```

::: predict
## Without control, a pendulum 1 m long falls away from upright with its angle growing as $e^{\sqrt{g/L}\,t}$. How long does its angle take to double? And for a 25 cm pendulum?

- [ ] 1 s and 0.25 s
- [x] 0.22 s and 0.11 s
- [ ] 0.32 s and 0.32 s
- [ ] 2.2 s and 1.1 s

::: reveal
The growth rate is $\sqrt{9.81/1}$ = 3.13 s⁻¹, so doubling takes ln 2/3.13 = 0.22 s. A quarter of the length doubles the rate to 6.26 s⁻¹ and halves the time to 0.11 s. That's why a long broomstick is easier to balance than a pencil: the controller has more time.
:::
:::

::: nameit
## The unstable plant

Linearized about upright, with the cart's acceleration a as the input,

$$\ddot\theta = \frac{g}{L}\theta - \frac{a}{L}$$

with poles at $\pm\sqrt{g/L}$: one in the right half plane.

## Angle feedback

Accelerating the cart toward the lean, $a = k_p\theta + k_d\dot\theta$, gives

$$\ddot\theta + \frac{k_d}{L}\dot\theta + \frac{k_p - g}{L}\theta = 0$$

stable when $k_p > g$ and $k_d > 0$, with $\omega_n = \sqrt{(k_p - g)/L}$ and $\zeta = k_d/(2\sqrt{L(k_p - g)})$. But nothing in this law cares where the cart is, so the pendulum stays up while the cart drifts off at constant speed.

## Full-state feedback

With the state $(x, \dot x, \theta, \dot\theta)$, feedback $a = -K\mathbf x$ on all four places all four poles (lesson 9), so the cart returns home too. The gains come out with a surprising sign: to move the cart left, the controller first moves it right, tipping the pendulum left so that it can follow. Systems with this "wrong-way" start are hard to control quickly.

## Linear design, nonlinear check

The gains are designed on the linearized model, then tested on the full equation $\ddot\theta = (g\sin\theta - a\cos\theta)/L$. Near upright they agree; far from it the linear design eventually fails.
:::

::: example
## A 0.5 m pendulum is controlled with $k_p$ = 20 m/s² per radian and $k_d$ = 4 m/s per radian per second. What are its natural frequency and damping?

::: solution
1. **Natural frequency.**
   $$\begin{aligned} \omega_n &= \sqrt{(20 - 9.81)/0.5} \\ &= 4.51\ \text{rad/s} \end{aligned}$$
2. **Damping.**
   $$\begin{aligned} \zeta &= \frac{4}{2\sqrt{0.5 \times 10.19}} \\ &= 0.886 \end{aligned}$$
3. **What that means.** It's a well-damped catch, but the cart will drift.

**Answer:** $\omega_n$ = 4.51 rad/s and ζ = 0.886.
:::
:::

::: example
## The full-state design in the Python step places the poles at −3, −4 and −5 ± j2 for L = 0.5 m. How does it do?

::: solution
1. **Gains.** Ackermann's formula gives
   $$\begin{aligned} K = (&-17.7, -16.5, \\ &-74.2, -16.7) \end{aligned}$$
2. **From 0.2 rad.** The nonlinear pendulum is upright and the cart home within 5 s, with peak cart acceleration 14.8 m/s².
3. **Larger starts.** The same gains recover from 0.7 rad (40°) but not from 0.9 rad, where the linear model is too far from the truth.

**Answer:** from 0.2 rad it balances and brings the cart home within 5 s, peaking at 14.8 m/s², and it recovers from 0.7 rad but not from 0.9 rad.
:::
:::

::: example
## Without control, how fast does a 0.5 m inverted pendulum fall away from upright?

::: solution
1. **Linearized equation.**
   $$\ddot\theta = (g/L)\theta$$
   so small angles grow as $e^{st}$.
2. **Growth rate.**
   $$\begin{aligned} s &= \sqrt{9.81/0.5} \\ &= 4.43\ \text{s}^{-1} \end{aligned}$$
3. **Doubling time.**
   $$\ln 2/4.43 = 0.16\ \text{s}$$
4. **What the controller needs.** It must act within a fraction of that, which is why balance loops run fast.

**Answer:** the angle doubles every 0.16 s.
:::
:::

::: check
kind: python

## Model the cart and pendulum, place the poles with Ackermann's formula, and test the design on the nonlinear pendulum.

```python starter
import numpy as np

def linear_model(L, g=9.81):
    # Cart and pendulum with the cart's acceleration a as the input. State (x, v, theta, omega),
    # theta measured from upright: x' = v, v' = a, theta' = omega, omega' = (g/L)*theta - a/L.
    # Return (A, B): a 4x4 array and a length-4 array.
    return np.zeros((4, 4)), np.zeros(4)

def place(A, B, poles):
    # Ackermann's formula: K = [0 0 0 1] @ inv([B, AB, A^2 B, A^3 B]) @ phi(A), where phi is
    # the monic polynomial with the given roots (np.poly gives its coefficients). Return K, real.
    return np.zeros(4)

def simulate(K, L, theta0, T=5.0, dt=1e-3, g=9.81):
    # The full nonlinear pendulum, omega' = (g*sin(theta) - a*cos(theta))/L, with a = -K @ state,
    # from rest at (0, 0, theta0, 0), integrated by RK4. Return (final state, largest |a|).
    return np.array([0.0, 0.0, theta0, 0.0]), 0.0
```

```python solution
import numpy as np

def linear_model(L, g=9.81):
    A = np.array([[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, g/L, 0]], dtype=float)
    B = np.array([0, 1, 0, -1/L], dtype=float)
    return A, B

def place(A, B, poles):
    n = len(B)
    C = np.column_stack([np.linalg.matrix_power(A, i) @ B for i in range(n)])
    c = np.real(np.poly(poles))
    phi = sum(c[i]*np.linalg.matrix_power(A, n - i) for i in range(n + 1))
    e = np.zeros(n); e[-1] = 1
    return e @ np.linalg.solve(C, phi)

def simulate(K, L, theta0, T=5.0, dt=1e-3, g=9.81):
    def f(s):
        a = -K @ s
        return np.array([s[1], a, s[3], (g*np.sin(s[2]) - a*np.cos(s[2]))/L])
    s = np.array([0.0, 0.0, theta0, 0.0])
    amax = abs(K @ s)
    for _ in range(int(round(T/dt))):
        k1 = f(s); k2 = f(s + dt/2*k1); k3 = f(s + dt/2*k2); k4 = f(s + dt*k3)
        s = s + dt/6*(k1 + 2*k2 + 2*k3 + k4)
        amax = max(amax, abs(K @ s))
    return s, amax
```

```python tests
A, B = linear_model(0.5)
assert A.shape == (4, 4) and abs(A[3, 2] - 19.62) < 1e-9 and abs(B[3] + 2.0) < 1e-12 and A[0, 1] == 1 and A[2, 3] == 1 and B[1] == 1, "For L = 0.5 m, A[3,2] should be g/L = 19.62 and B should be (0, 1, 0, -2)."
poles = [-3, -4, -5 + 2j, -5 - 2j]
K = place(A, B, poles)
ev = np.sort_complex(np.linalg.eigvals(A - np.outer(B, K)))
assert np.allclose(ev, np.sort_complex(np.array(poles)), atol=1e-6), f"A - BK should have eigenvalues {poles}; got {ev}."
s, amax = simulate(K, 0.5, 0.2)
assert np.max(np.abs(s)) < 1e-3, f"From 0.2 rad the pendulum should be balanced and the cart back home after 5 s; final state {s}."
assert 5 < amax < 200, f"The largest cart acceleration should be a sensible tens of m/s^2; got {amax:.1f}."
s2, _ = simulate(np.zeros(4), 0.5, 0.01, T=1.5)
assert s2[2] > 0.5, "With no control the pendulum should fall: from 0.01 rad it passes 0.5 rad within 1.5 s."
```

::: right
Right. Your controller catches the pendulum from 0.2 rad and brings the cart home, with the poles exactly where you put them.
:::
:::

::: check
given: L = 0.25 | 0.5 | 1 | 2
answer: sqrt(9.81/L)
unit: s⁻¹
tolerance: 0.5%

## How fast does an uncontrolled pendulum {L} m long fall away from upright (the growth rate of its angle)?

::: right
Right. $\sqrt{g/L}$ = {answer} s⁻¹.
:::

::: misses
- [9.81/L] Take the square root.
- [any] Not yet. The unstable pole of $\ddot\theta = (g/L)\theta$.
:::
:::

::: check
given: L = 0.25 | 0.5 | 1 | 2
answer: ln(2)/sqrt(9.81/L)
unit: s
tolerance: 0.5%

## How long does an uncontrolled {L} m pendulum take to double its angle?

::: right
Right. $\ln 2/\sqrt{g/L}$ = {answer} s.
:::

::: misses
- [1/sqrt(9.81/L)] That's the time constant; doubling takes ln 2 of it.
- [any] Not yet. Solve $e^{\sigma t} = 2$.
:::
:::

::: check
given: L = 0.3 | 0.5 | 1; P = 15 | 25 | 40
answer: sqrt((P - 9.81)/L)
unit: rad/s
tolerance: 0.5%

## A {L} m pendulum is caught with $k_p$ = {P} m/s² per radian. What's the closed loop's natural frequency?

::: right
Right. $\sqrt{(k_p - g)/L}$ = {answer} rad/s.
:::

::: misses
- [sqrt(P/L)] Gravity works against the controller: subtract g.
- [any] Not yet. Collect the θ terms.
:::
:::

::: check
given: L = 0.3 | 0.5 | 1; P = 15 | 25 | 40; D = 2 | 4 | 8
answer: D/(2*sqrt(L*(P - 9.81)))
tolerance: 0.5%

## The same {L} m pendulum with $k_p$ = {P} has $k_d$ = {D}. What's the damping ratio?

::: right
Right. $k_d/(2\sqrt{L(k_p - g)})$ = {answer}.
:::

::: misses
- [D/(2*sqrt(L*P))] Use $k_p - g$.
- [any] Not yet. $2\zeta\omega_n = k_d/L$.
:::
:::

::: check
kind: parts
given: L = 0.25 | 0.5 | 1

## An inverted pendulum of length {L} m is left uncontrolled.

::: part
answer: sqrt(9.81/L)
unit: s⁻¹
tolerance: 0.5%

### At what rate s, in s⁻¹, does a small tilt grow as $e^{st}$?

::: misses
- [any] $\sqrt{g/L}$.
:::
:::

::: part
answer: ln(2)/sqrt(9.81/L)
unit: s
tolerance: 0.5%

### How long does the tilt take to double?

::: misses
- [any] $\ln 2/s$.
:::
:::
:::

::: check
kind: parts
given: L = 0.5 | 1; kp = 15 | 20 | 30; kd = 2 | 4

## A pendulum of length {L} m is held up with $k_p$ = {kp} m/s² per radian and $k_d$ = {kd} m/s per rad/s, giving $L\ddot\theta = (g - k_p)\theta - k_d\dot\theta$... rewritten as $L\ddot\theta + k_d\dot\theta + (k_p - g)\theta = 0$.

::: part
answer: sqrt((kp - 9.81)/L)
unit: rad/s
tolerance: 0.5%

### What is its natural frequency?

::: misses
- [any] $\sqrt{(k_p - g)/L}$.
:::
:::

::: part
answer: kd/(2*sqrt(L*(kp - 9.81)))
tolerance: 0.5%

### What is its damping ratio?

::: misses
- [any] $k_d/(2\sqrt{L(k_p - g)})$.
:::
:::
:::

::: explain
## Why does feeding back only the pendulum's angle let the cart drift away?

::: model
Angle feedback accelerates the cart whenever the pendulum leans, which is enough to bring the pendulum upright and hold it there. But once it's upright with no angular motion, the control law asks for zero acceleration, and that's satisfied by a cart at rest anywhere or by a cart rolling at any constant speed. Nothing in the law measures the cart's position or velocity, so those two states are left uncontrolled, and any small push sets the cart drifting. Feeding back the cart's position and velocity too gives the controller a reason to bring it home, which it does by deliberately tipping the pendulum toward home and then following it.
:::
:::

::: practice

::: check
given: L = 0.05 | 0.1 | 0.25 | 0.5 | 1 | 2 | 10
answer: sqrt(9.81/L)
unit: s⁻¹
tolerance: 0.5%

## Falling rate, L = {L} m?

::: misses
- [any] $\sqrt{g/L}$.
:::
:::

::: check
given: L = 0.1 | 5; P = 12 | 100
answer: sqrt((P - 9.81)/L)
unit: rad/s
tolerance: 0.5%

## $\omega_n$: L = {L} m, $k_p$ = {P}?

::: misses
- [any] $\sqrt{(k_p - g)/L}$.
:::
:::
:::
