---
title: "Project: a DC-motor position servo"
heading: Modeling a DC motor with angle, speed and current as states, designing state feedback and an observer by pole placement, and simulating the observer-based servo with a saturating 12 V amplifier to check overshoot, settling and estimator convergence
eyebrow: S9 · Lesson 51 · Project
xp: 80
---

::: hook
This project puts the second half of the course to work on one real plant: the DC motor from lesson 2, now turning a shaft whose angle you want to control, with only the angle measured. You'll write its three-state model, place the controller's and the observer's poles, and simulate the whole loop with an amplifier that clips at ±12 V. The tests check what a bench test would: overshoot and settling time for a small step, graceful behavior when a large step saturates the amplifier, and an observer that finds the true state after starting out wrong.
:::

::: predict
## The design places the controller's poles at −60 ± j60 and −600. A 1 rad step then needs at most 4.4 V. What happens on a 5 rad step with a 12 V amplifier?

- [x] The amplifier clips at 12 V for a while, the motor slews at its limit, and the response settles more slowly but without much extra overshoot, since nothing in this controller winds up
- [ ] The loop goes unstable
- [ ] The response is exactly the 1 rad response scaled by five
- [ ] The motor never reaches 5 rad

::: reveal
A linear loop would need 22 V for that step, so the input clips and the early response is slower than the linear design. Because this controller has no integrator, there's no windup: once the error is small enough for the command to come back inside ±12 V, the loop is linear again and finishes like the small-step response. The test requires settling within 2% of 5 rad in under 0.2 s.
:::
:::

::: nameit
## The model

With states x = (θ, ω, i) and input voltage V:

$$\dot\theta = \omega, \qquad J\dot\omega = K_ti - b\omega, \qquad L\dot{i} = V - Ri - K_e\omega$$

$$A = \begin{pmatrix} 0 & 1 & 0 \\ 0 & -b/J & K_t/J \\ 0 & -K_e/L & -R/L \end{pmatrix}, \quad B = \begin{pmatrix} 0 \\ 0 \\ 1/L \end{pmatrix}, \quad C = \begin{pmatrix} 1 & 0 & 0 \end{pmatrix}$$

For R = 2 Ω, L = 0.5 mH, $K_t = K_e$ = 0.05, J = 2 × 10⁻⁵ kg·m², b = 10⁻⁵: poles at 0, −64.0 and −3936 s⁻¹.

## The design

- **Controller:** dominant poles at −60 ± j60 (ζ = 0.707, $\omega_n$ = 84.9 rad/s) and a third at −600, ten times farther out. Ackermann (lesson 50) gives K = (0.864, −0.0342, −1.640) and $k_r$ = 0.864.
- **Observer:** −300 ± j300 and −5000, five times faster than the controller, computed by duality as `place(A.T, C, poles)`.
- **Simulation:** RK4 on the plant and observer together, with $u = \text{clip}(k_rr - K\hat{x}, \pm 12\text{ V})$, the observer driven by the clipped u that the plant actually receives.

## Why the observer gets the clipped input

If the observer were fed the unclipped command while the plant got the clipped one, the model and the plant would diverge every time the amplifier saturated, and the estimate would be wrong exactly when it matters. Feeding the model the actual applied input keeps the estimation error obeying $\dot{e} = (A - LC)e$, saturated or not.
:::

::: example
## Why is the current gain in K negative?

::: solution
1. **The two poles.** The motor's electrical pole is at −3936, but the design asks for a third pole at −600.
2. **Feedback can slow a pole.** State feedback can slow a pole as well as speed it up. The current row of A − BK has on its diagonal
   $$\begin{aligned} -R/L - k_3/L &= -4000 + 3280 \\ &= -720 \end{aligned}$$
3. **What the negative gain does.** A negative current gain feeds back positively on current, so the controller weakens the motor's natural current regulation.
4. **The alternative.** Placing the third pole near the electrical one instead would need much larger gains and a noisier current loop.

**Answer:** the design puts the third pole at −600, much slower than the motor's electrical pole at −3936, and a negative current gain is what slows it.
:::
:::

::: example
## What does the observer do in the first few milliseconds after it starts 0.1 rad wrong?

::: solution
1. **Error dynamics.** The error obeys $\dot{e} = (A - LC)e$, with poles at
   $$-300 \pm j300, \quad -5000$$
2. **The fast pole.** It removes part of the error within about a millisecond.
3. **The slower pair.** It decays as $e^{-300t}$, falling to 0.1% of the initial error by about 23 ms, well before the controller's 72 ms settling.
4. **What the test checks.** That the largest error is below 0.001 after 50 ms.

**Answer:** the fast pole removes part of the error within a millisecond, and the rest decays as $e^{-300t}$, down to 0.1% by about 23 ms.
:::
:::

::: check
kind: python

## Step 1. Write `motor_model(R, L, Kt, J, b)`: the three-state motor.

```python starter
import numpy as np

def motor_model(R, L, Kt, J, b):
    # State x = (theta, omega, i), input V, output theta. Return (A, B, C) as numpy arrays
    # with shapes (3, 3), (3,) and (3,). Use Ke = Kt.
    return np.zeros((3, 3)), np.zeros(3), np.zeros(3)

A, B, C = motor_model(2, 0.5e-3, 0.05, 2e-5, 1e-5)
print(A)
```

```python solution
import numpy as np

def motor_model(R, L, Kt, J, b):
    A = np.array([[0.0, 1.0, 0.0],
                  [0.0, -b/J, Kt/J],
                  [0.0, -Kt/L, -R/L]])
    B = np.array([0.0, 0.0, 1.0/L])
    C = np.array([1.0, 0.0, 0.0])
    return A, B, C

A, B, C = motor_model(2, 0.5e-3, 0.05, 2e-5, 1e-5)
print(A)
```

```python tests
import numpy as np
A, B, C = motor_model(2, 0.5e-3, 0.05, 2e-5, 1e-5)
ev = np.sort(np.linalg.eigvals(A).real)
assert np.allclose(ev, [-3936.4835, -64.0165, 0], atol=1e-3), f"The motor's poles are 0 (the angle integrates speed), −64.0 and −3936; got {ev}."
s = 30j
G = C @ np.linalg.solve(s*np.eye(3) - A, B)
want = 0.05/(s*((2e-5*s + 1e-5)*(0.5e-3*s + 2) + 0.05**2))
assert abs(G - want) < 1e-9*abs(want), "θ/V must equal Kt/(s((Js + b)(Ls + R) + Kt Ke)) at every frequency."
A2, B2, C2 = motor_model(1, 2e-3, 0.1, 1e-4, 0)
assert np.isclose(A2[1, 2], 1000) and np.isclose(A2[2, 1], -50) and np.isclose(B2[2], 500), "Check the entries: Kt/J in the speed row, −Ke/L and 1/L in the current row."
```

::: right
Right. Your model has the motor's poles and its exact angle-per-volt transfer function.
:::
:::

::: check
kind: python

## Step 2. Write `design(A, B, C, ctrl_poles, obs_poles)`: state feedback, observer and reference gain.

```python starter
import numpy as np

def design(A, B, C, ctrl_poles, obs_poles):
    # Return (K, L, kr): state-feedback gains placing eig(A - B K) at ctrl_poles, observer gains
    # placing eig(A - L C) at obs_poles, and the reference gain kr giving zero steady error.
    n = len(B)
    return np.zeros(n), np.zeros(n), 0.0
```

```python solution
import numpy as np

def place(A, B, poles):
    A = np.asarray(A, float); B = np.asarray(B, float).reshape(-1, 1); n = A.shape[0]
    Wr = np.hstack([np.linalg.matrix_power(A, k) @ B for k in range(n)])
    p = np.real(np.poly(poles))
    pA = sum(c*np.linalg.matrix_power(A, n - i) for i, c in enumerate(p))
    e = np.zeros(n); e[-1] = 1
    return e @ np.linalg.solve(Wr, pA)

def design(A, B, C, ctrl_poles, obs_poles):
    K = place(A, B, ctrl_poles)
    L = place(A.T, C, obs_poles)
    kr = -1.0/(C @ np.linalg.solve(A - np.outer(B, K), B))
    return K, L, kr
```

```python tests
import numpy as np
R, Lm, Kt, J, b = 2.0, 0.5e-3, 0.05, 2e-5, 1e-5
A = np.array([[0, 1, 0], [0, -b/J, Kt/J], [0, -Kt/Lm, -R/Lm]]); B = np.array([0, 0, 1/Lm]); C = np.array([1.0, 0, 0])
pc = [-60 + 60j, -60 - 60j, -600]; po = [-300 + 300j, -300 - 300j, -5000]
K, L, kr = design(A, B, C, pc, po)
K = np.asarray(K).ravel(); L = np.asarray(L).ravel()
got = np.sort_complex(np.linalg.eigvals(A - np.outer(B, K)))
assert np.allclose(got, np.sort_complex(np.array(pc)), atol=1e-6), f"eig(A − BK) must be {pc}; got {got}."
got = np.sort_complex(np.linalg.eigvals(A - np.outer(L, C)))
assert np.allclose(got, np.sort_complex(np.array(po)), atol=1e-4), f"eig(A − LC) must be {po}; got {got}."
dc = kr*(C @ np.linalg.solve(-(A - np.outer(B, K)), B))
assert abs(dc - 1) < 1e-9, f"With kr the closed loop's DC gain must be 1; got {dc}."
assert np.isclose(K[0], kr), "For a position servo whose first state is the output, kr equals the position gain."
```

::: right
Right. Both sets of poles land exactly, and the loop has unit DC gain.
:::
:::

::: check
kind: python

## Step 3. Write `simulate(...)`: the observer-based servo with a saturating amplifier.

```python starter
import numpy as np

def simulate(A, B, C, K, L, kr, r, umax, T, dt, x0=None):
    # Simulate the plant with an observer-based controller u = clip(kr*r - K @ xhat, -umax, umax),
    # plant starting at x0 (zeros if None) and observer at zero. RK4 with step dt up to time T.
    # Return (t, y, u, e): time, output, applied input, and max |x - xhat| at each step.
    t = np.arange(0, T, dt)
    return t, np.zeros(len(t)), np.zeros(len(t)), np.zeros(len(t))
```

```python solution
import numpy as np

def simulate(A, B, C, K, L, kr, r, umax, T, dt, x0=None):
    n = len(B)
    x = np.zeros(n) if x0 is None else np.array(x0, float)
    xh = np.zeros(n)
    def f(x, xh):
        u = min(max(kr*r - K @ xh, -umax), umax)
        y = C @ x
        return A @ x + B*u, A @ xh + B*u + L*(y - C @ xh), u
    t = np.arange(0, T, dt)
    ys = np.zeros(len(t)); us = np.zeros(len(t)); es = np.zeros(len(t))
    for k in range(len(t)):
        k1 = f(x, xh)
        ys[k] = C @ x; us[k] = k1[2]; es[k] = np.max(np.abs(x - xh))
        k2 = f(x + dt/2*k1[0], xh + dt/2*k1[1])
        k3 = f(x + dt/2*k2[0], xh + dt/2*k2[1])
        k4 = f(x + dt*k3[0], xh + dt*k3[1])
        x = x + dt/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0])
        xh = xh + dt/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])
    return t, ys, us, es
```

```python tests
import numpy as np
def settle(t, y, target, band):
    out = np.where(np.abs(y - target) > band)[0]
    if len(out) == 0: return 0.0
    return t[out[-1] + 1] if out[-1] + 1 < len(t) else np.inf
A = np.array([[0, 1, 0], [0, -0.5, 2500], [0, -100, -4000]]); B = np.array([0, 0, 2000.0]); C = np.array([1.0, 0, 0])
K = np.array([0.864, -0.03423195, -1.64025]); L = np.array([1599.5, -3470799.75, 5752050.0]); kr = 0.864
t, y, u, e = simulate(A, B, C, K, L, kr, 1.0, 12, 0.15, 5e-5)
os = (y.max() - 1)*100
ts = settle(t, y, 1, 0.02)
assert 3.5 < os < 5, f"A 1 rad step should overshoot about 4.3%; got {os:.2f}%."
assert ts < 0.08, f"It should settle within 2% in about 72 ms; got {ts*1000:.1f} ms."
assert np.abs(u).max() < 5, "A 1 rad step needs under 5 V: the amplifier stays linear."
t, y, u, e = simulate(A, B, C, K, L, kr, 5.0, 12, 0.3, 5e-5)
assert np.abs(u).max() <= 12 + 1e-12 and np.abs(u).max() > 11.99, "A 5 rad step asks for more than 12 V: the input must be clipped at ±12 V."
ts = settle(t, y, 5, 0.1)
assert abs(y[-1] - 5) < 1e-3 and ts < 0.2, f"Even saturated, the servo must reach 5 rad within 2% before 0.2 s; it settled at {ts*1000:.0f} ms."
t, y, u, e = simulate(A, B, C, K, L, kr, 0.0, 12, 0.05, 5e-5, x0=[0.1, 0, 0])
assert e[0] > 0.09 and e[-1] < 1e-3, f"Started 0.1 rad off, the observer's error must shrink below 0.001 within 50 ms; it ended at {e[-1]:.2e}."
```

::: right
Right. The servo overshoots 4.3% and settles in 72 ms, survives a saturating 5 rad step, and its observer finds the true state.
:::
:::

::: explain
## Why can the controller and the observer be designed separately even though the controller uses the observer's estimate?

::: model
Write the closed loop in terms of the plant's state x and the estimation error e = x − x̂. The control law $u = -K\hat{x} = -Kx + Ke$ makes $\dot{x} = (A - BK)x + BKe$, while the error obeys $\dot{e} = (A - LC)e$, which doesn't involve x or K at all. The system matrix is block triangular, so its eigenvalues are those of A − BK together with those of A − LC. The controller's poles are exactly where they were designed for full-state feedback, and the observer's are where they were placed, with the error acting only as a decaying disturbance on the controlled plant.
:::
:::

::: practice

::: check
given: R = 1 | 3; L = 0.2 | 1; K = 0.03 | 0.08
answer: -R/(L*1e-3)
unit: s^-1
tolerance: 0.5%

## In the motor model with R = {R} Ω, L = {L} mH and $K_t$ = {K}, what's the entry $a_{33}$?

::: misses
- [any] $-R/L$.
:::
:::

::: check
given: w = 30 | 85 | 200
answer: w*sqrt(2)/2
unit: rad/s
tolerance: 0.5%

## Dominant poles with ζ = 0.707 and $\omega_n$ = {w}: what's their real part's magnitude?

::: misses
- [any] $\zeta\omega_n$.
:::
:::

::: check
given: K = 0.5 | 2; R = 1 | 3; L = 0.3 | 1
answer: -R/(L*1e-3) - K/(L*1e-3)
unit: s^-1
tolerance: 0.5%

## With a current gain $k_3$ = {K} and $B_3 = 1/L$, what's the current row's diagonal entry of A − BK (R = {R} Ω, L = {L} mH)?

::: misses
- [any] $-R/L - k_3/L$.
:::
:::
:::
