---
title: "Motor controller: current and speed loops"
heading: Controlling a motor with two nested loops, a fast current loop whose PI gains cancel the winding's pole, a slower speed loop that commands current, limits on current and voltage, integrator windup and conditional integration, and a simulated drive that meets its specifications
eyebrow: D13 · Lesson 10 · Motor controller
xp: 120
---

::: hook
Industrial drives almost all use the same structure: an inner loop that controls the motor's current, and therefore its torque, and an outer loop that controls speed by asking for current. The inner loop is fast and protects the hardware, since limiting the current demand limits the torque and the heat; the outer loop is slower and sees a simple plant, an inertia driven by a torque it can command. Limits make the loops nonlinear, and a PI controller that ignores its limits winds up its integral and overshoots badly. This lab builds the whole drive and makes it meet a specification.
:::

::: play
- The speed loop's response to a step in demand, assuming the current loop is perfect and nothing saturates, for a speed-loop bandwidth $f_s$ and a PI zero placed at $\omega_s/r$.
- Pushing the zero closer to the bandwidth (smaller r) gives stronger integral action, which rejects load torque faster, but at the cost of overshoot.
- The readout shows the current this linear design would ask for at the start of a 250 rad/s step. It's far above the motor's 8 A limit, so in practice the drive saturates, which the linear picture can't show and the lab can.

```sim plot
view: graph
x: t = 0..80
y: y = 0..1.4
slider: fs = 10..200 step 5 = 50
slider: r = 2..20 step 0.5 = 5
plot: 1 - Re(exp(-((0.5 + (2*pi*fs))/2)*(t/1000))*(cosh(sqrt(((0.5 + (2*pi*fs))/2)^2 - ((2*pi*fs)^2/r) + 1e-9)*(t/1000)) + (((0.5 + (2*pi*fs))/2) - (2*pi*fs))*sinh(sqrt(((0.5 + (2*pi*fs))/2)^2 - ((2*pi*fs)^2/r) + 1e-9)*(t/1000))/sqrt(((0.5 + (2*pi*fs))/2)^2 - ((2*pi*fs)^2/r) + 1e-9))) | samples: 800 | label: speed, fraction of the step (t in ms)
plot: 1 + 0*t | dashed | color: ch3 | label: demand
readout: initial current demand for 250 rad/s, A = 2e-5*2*pi*fs/0.05*250 | digits: 3
```

::: predict
## The drive's current is limited to 8 A, the motor's K is 0.05 N·m/A and its inertia 2 × 10⁻⁵ kg·m². At best, how long does it take to reach 250 rad/s from rest?

- [ ] 1.25 ms
- [x] 12.5 ms
- [ ] 125 ms
- [ ] 50 ms

::: reveal
8 A gives 0.4 N·m of torque, which accelerates the rotor at 0.4/(2 × 10⁻⁵) = 20,000 rad/s². Reaching 250 rad/s takes 250/20,000 = 12.5 ms however high the loop gains are. For most of a large step the drive simply runs at its current limit, and the controller's job is to come out of the limit smoothly.
:::
:::

::: nameit
## The current loop

Seen from the voltage, the winding is $1/(Ls + R)$, with the back-EMF as a slowly changing disturbance. A PI controller $k_p + k_i/s$ with

$$k_p = L\omega_c, \qquad k_i = R\omega_c$$

has its zero at $R/L$, exactly on the winding's pole, so the closed current loop is a first-order lag of bandwidth $\omega_c$, here 2π × 1 kHz, a time constant of 0.16 ms.

## The speed loop

With the current loop much faster, the speed plant is $K/(Js + B)$: a commanded current makes torque Ki. A PI with $k_p = J\omega_s/K$ crosses over near $\omega_s$, and $k_i = k_p\omega_s/r$ puts its zero r times lower. The bandwidths are separated by a factor of 20 (50 Hz against 1 kHz), so each loop sees the other as nearly ideal.

## Limits and windup

The speed controller's output is clamped to ±8 A and the current controller's to the 24 V supply. While a controller is clamped, its integral keeps growing if nothing stops it: **windup**. When the speed finally arrives, the oversized integral holds the current high and the speed overshoots. **Conditional integration** stops the integral whenever the output is clamped, so the controller leaves the limit with a sensible integral. The lab compares the two: about 3% overshoot with it, over 30% without.
:::

::: example
## What PI gains does the lab use?

::: solution
1. **Current loop, proportional gain.** $k_p = L\omega_c$:
   $$\begin{aligned} k_p &= 1\ \text{mH} \times 2\pi \times 1000 \\ &= 6.28\ \text{V/A} \end{aligned}$$
2. **Current loop, integral gain.** $k_i = R\omega_c$:
   $$\begin{aligned} k_i &= 1\ \Omega \times 2\pi \times 1000 \\ &= 6283\ \text{V/(A·s)} \end{aligned}$$
3. **Speed loop, proportional gain.** $k_p = J\omega_s/K$, with $\omega_s = 2\pi \times 50$:
   $$\begin{aligned} k_p &= \frac{2 \times 10^{-5} \times 2\pi \times 50}{0.05} \\ &= 0.126\ \text{A per rad/s} \end{aligned}$$
4. **Speed loop, integral gain.**
   $$\begin{aligned} k_i &= \frac{k_p\omega_s}{5} \\ &= \frac{2 \times 10^{-5}(2\pi \times 50)^2}{5 \times 0.05} \\ &= 7.90\ \text{A/rad} \end{aligned}$$

**Answer:** the current loop uses $k_p$ = 6.28 V/A and $k_i$ = 6283 V/(A·s); the speed loop uses $k_p$ = 0.126 A per rad/s and $k_i$ = 7.90 A/rad.
:::
:::

::: example
## A 0.1 N·m load lands while the motor holds 250 rad/s. What current must the drive add, and what did the lab's drive do?

::: solution
1. **Extra current.**
   $$\frac{0.1}{0.05} = 2\ \text{A}$$
   more.
2. **What the lab's drive did.** The speed dips to about 237.7 rad/s while the speed loop's integral builds up that 2 A, and it's back within 1% about 30 ms after the step.
3. **Without the integral.** A proportional loop would settle with an error of
   $$\frac{2\ \text{A}}{0.126\ \text{A per rad/s}} = 16\ \text{rad/s}$$

**Answer:** 2 A more; the lab's drive dipped to about 237.7 rad/s and was back within 1% about 30 ms later.
:::
:::

::: check
kind: python

## Build the drive: two PI loops with limits and anti-windup, meeting the specification.

```python starter
import numpy as np

P = dict(R=1.0, L=1e-3, K=0.05, J=2e-5, B=1e-5)
V_MAX, I_MAX = 24.0, 8.0

def motor_step(i, w, v, tl, dt, p=P):
    # One small Euler step of the motor from lesson 9.
    di = (v - p['R']*i - p['K']*w)/p['L']
    dw = (p['K']*i - p['B']*w - tl)/p['J']
    return i + di*dt, w + dw*dt

class PI:
    def __init__(self, kp, ki, lo, hi, antiwindup=True):
        self.kp, self.ki, self.lo, self.hi, self.antiwindup = kp, ki, lo, hi, antiwindup
        self.integral = 0.0

    def update(self, error, dt):
        # Output kp*error + integral, clamped to lo..hi. Then add ki*error*dt to the integral,
        # but with antiwindup only when the output wasn't clamped. Return the clamped output.
        return 0.0

def gains(wc, ws, p=P):
    # Current loop: kp = L*wc, ki = R*wc, cancelling the winding's pole.
    # Speed loop: kp = J*ws/K, ki = kp*ws/5.
    # Return (kp_i, ki_i, kp_w, ki_w).
    return 0.0, 0.0, 0.0, 0.0

def run_drive(w_ref, t_end, tl=0.0, tl_at=1e9, antiwindup=True, dt=1e-5,
              wc=2*np.pi*1000, ws=2*np.pi*50, p=P):
    # Each step: the speed PI turns w_ref - w into a current demand (limited to ±I_MAX), the
    # current PI turns that demand minus i into a voltage (limited to ±V_MAX), and motor_step
    # advances the motor, with load torque tl from time tl_at on. Start at rest.
    # Return arrays t, w, i, v, one entry per step.
    n = int(round(t_end/dt))
    return np.arange(n)*dt, np.zeros(n), np.zeros(n), np.zeros(n)
```

```python solution
import numpy as np

P = dict(R=1.0, L=1e-3, K=0.05, J=2e-5, B=1e-5)
V_MAX, I_MAX = 24.0, 8.0

def motor_step(i, w, v, tl, dt, p=P):
    # One small Euler step of the motor from lesson 9.
    di = (v - p['R']*i - p['K']*w)/p['L']
    dw = (p['K']*i - p['B']*w - tl)/p['J']
    return i + di*dt, w + dw*dt

class PI:
    def __init__(self, kp, ki, lo, hi, antiwindup=True):
        self.kp, self.ki, self.lo, self.hi, self.antiwindup = kp, ki, lo, hi, antiwindup
        self.integral = 0.0

    def update(self, error, dt):
        u = self.kp*error + self.integral
        out = min(self.hi, max(self.lo, u))
        if not self.antiwindup or out == u:
            self.integral += self.ki*error*dt
        return out

def gains(wc, ws, p=P):
    kp_w = p['J']*ws/p['K']
    return p['L']*wc, p['R']*wc, kp_w, kp_w*ws/5

def run_drive(w_ref, t_end, tl=0.0, tl_at=1e9, antiwindup=True, dt=1e-5,
              wc=2*np.pi*1000, ws=2*np.pi*50, p=P):
    kp_i, ki_i, kp_w, ki_w = gains(wc, ws, p)
    speed = PI(kp_w, ki_w, -I_MAX, I_MAX, antiwindup)
    current = PI(kp_i, ki_i, -V_MAX, V_MAX, antiwindup)
    n = int(round(t_end/dt))
    t, W, I, Vv = np.arange(n)*dt, np.zeros(n), np.zeros(n), np.zeros(n)
    i = w = 0.0
    for k in range(n):
        i_ref = speed.update(w_ref - w, dt)
        v = current.update(i_ref - i, dt)
        i, w = motor_step(i, w, v, tl if t[k] >= tl_at else 0.0, dt, p)
        W[k], I[k], Vv[k] = w, i, v
    return t, W, I, Vv
```

```python tests
_c = PI(2, 10, -5, 5)
assert _c.update(1, 0.1) == 2 and abs(_c.update(1, 0.1) - 3) < 1e-12, "The output uses the integral so far, then the integral grows by ki*e*dt."
_before = _c.integral
assert _c.update(10, 0.1) == 5 and _c.integral == _before, "A clamped output stops the integral (anti-windup)."
_g = gains(2*np.pi*1000, 2*np.pi*50)
assert np.allclose(_g, (6.2832, 6283.2, 0.12566, 7.8957), rtol=1e-4), f"Gains: 6.283 V/A, 6283 V/(A·s), 0.1257 A·s/rad, 7.896 A/rad; got {_g}."
_t, _w, _i, _v = run_drive(250, 0.3, tl=0.1, tl_at=0.15)
_os = (np.max(_w[_t < 0.15]) - 250)/250*100
assert _os < 5, f"Overshoot should stay under 5%; got {_os:.1f}%."
_late = np.abs(_w[(_t > 0.04) & (_t < 0.15)] - 250)
assert np.max(_late) < 5, "Within 40 ms the speed should be within 2% of 250 rad/s."
assert np.max(np.abs(_i)) < I_MAX*1.02, f"The current must respect the 8 A limit; peak {np.max(np.abs(_i)):.2f} A."
assert np.max(np.abs(_w[_t > 0.2] - 250)) < 2.5, "After the load step, the integral action must restore the speed within 1% by 0.2 s."
_t2, _w2, _i2, _v2 = run_drive(250, 0.15, antiwindup=False)
assert (np.max(_w2) - 250)/250 > 0.2, "Without anti-windup the speed integral winds up during the current limit and overshoots badly."
```

::: right
Right. Your drive reaches 250 rad/s with under 5% overshoot inside its current limit and shrugs off a load step, and you've seen what windup does without the fix.
:::
:::

::: check
given: L = 0.2 | 1 | 5; f = 500 | 1000 | 2000
answer: L*1e-3*2*pi*f
unit: V/A
tolerance: 0.5%

## A current loop for a {L} mH winding should have a {f} Hz bandwidth. What proportional gain cancels the winding's pole?

::: right
Right. $k_p = L\omega_c$ = {answer} V/A.
:::

::: misses
- [L*1e-3*f] Use the angular frequency, 2πf.
- [any] Not yet. $k_p = L\omega_c$, with $k_i = R\omega_c$.
:::
:::

::: check
given: I = 4 | 8 | 20; K = 0.02 | 0.05 | 0.1; J = 1 | 2 | 10; w = 100 | 250
answer: J*1e-5*w/(K*I)*1000
unit: ms
tolerance: 0.5%

## A drive limited to {I} A spins a rotor of {J} × 10⁻⁵ kg·m² with K = {K} N·m/A. Ignoring friction and load, what's the shortest time to reach {w} rad/s from rest?

::: right
Right. $J\omega/(KI_\max)$ = {answer} ms.
:::

::: misses
- [J*1e-5*w/I*1000] The torque is K times the current.
- [any] Not yet. Speed over the largest acceleration $KI_\max/J$.
:::
:::

::: check
given: T = 0.02 | 0.1 | 0.3; K = 0.02 | 0.05 | 0.1; k = 0.05 | 0.126 | 0.5
answer: T/K/k
unit: rad/s
tolerance: 0.5%

## A proportional-only speed loop with gain {k} A per rad/s carries a load of {T} N·m on a motor with K = {K}. What steady speed error does it leave?

::: right
Right. The load needs $T_L/K$ amperes, which a proportional loop only produces from an error of $T_L/(Kk_p)$ = {answer} rad/s.
:::

::: misses
- [T*k/K] The error is the needed current divided by the gain.
- [any] Not yet. Needed current over proportional gain.
:::
:::

::: check
kind: parts
given: L = 0.5 | 1 | 2; R = 0.5 | 1; fc = 500 | 1000 | 2000

## A current loop around a motor winding ($L$ = {L} mH, $R$ = {R} Ω) uses a PI controller whose zero cancels the winding's pole, for a {fc} Hz crossover.

::: part
answer: 2*pi*fc*L*1e-3
unit: Ω
tolerance: 0.5%

### What proportional gain (V/A) does it need?

::: misses
- [fc*L*1e-3] Use $\omega_c = 2\pi f_c$.
- [any] Not yet. $k_p = \omega_cL$.
:::
:::

::: part
answer: 2*pi*fc*R
tolerance: 0.5%

### What integral gain (V/(A·s)) puts the zero on the pole?

::: misses
- [2*pi*fc*L*1e-3*L*1e-3/R] The zero $k_i/k_p$ must equal $R/L$: $k_i = k_pR/L$.
- [any] Not yet. $k_i = k_pR/L = \omega_cR$.
:::
:::

::: right
Right. With the pole cancelled, the loop is a pure integrator crossing at {fc} Hz.
:::
:::

::: check
given: fc = 500 | 1000 | 2000; r = 5 | 10 | 20
answer: fc/r
unit: Hz
tolerance: 0.5%

## A cascaded drive's current loop crosses over at {fc} Hz. The speed loop is set {r} times slower so the loops don't interact. What is the speed loop's crossover?

::: right
Right: {answer}. The speed loop then sees the current loop as nearly instant.
:::

::: misses
- [fc*r] The outer loop must be slower, not faster.
- [any] Not yet. Divide by {r}.
:::
:::

::: explain
## Why does a PI speed controller overshoot after a large step if its integral isn't stopped while the current is limited?

::: model
During a large speed step, the speed controller asks for far more current than the limit allows, so the motor accelerates at the limit for a while and the speed error stays large. If the integral keeps accumulating that large error the whole time, it grows far beyond what the final steady state needs. When the speed reaches its target and the error drops to zero, the output is still dominated by that oversized integral, so the controller keeps demanding full current and the speed overshoots until the error has been negative long enough to unwind it. Stopping the integral while the output is clamped keeps it near the value it should have, so the speed arrives without a large overshoot.
:::
:::

::: practice

::: check
given: L = 0.05 | 20; f = 100 | 5000
answer: L*1e-3*2*pi*f
unit: V/A
tolerance: 0.5%

## Current-loop $k_p$: {L} mH, {f} Hz?

::: misses
- [any] $L\omega_c$.
:::
:::

::: check
given: I = 1 | 50; K = 0.01 | 0.5; J = 0.5 | 100; w = 50 | 1000
answer: J*1e-5*w/(K*I)*1000
unit: ms
tolerance: 0.5%

## Time to {w} rad/s at {I} A, K = {K}, J = {J} × 10⁻⁵?

::: misses
- [any] $J\omega/(KI_\max)$.
:::
:::
:::
