---
title: "PM motor drive project: dq model, current loops and speed control"
heading: Writing a permanent-magnet synchronous motor's dq model in Python, closing current loops with PI regulators and decoupling so the q current follows a first-order lag at any speed, and closing a speed loop with a current limit, comparing its step response with and without anti-windup
eyebrow: S12 · Lesson 51 · PM motor drive project
xp: 80
---

::: hook
Every servo drive, electric-vehicle inverter and drone controller runs the same structure: fast inner loops that make the motor's dq currents follow their commands, and an outer loop that turns a speed or position error into a current command, limited to what the motor and inverter can stand. In this project you'll build that structure for an 8-pole surface PM motor, see why the decoupling terms make the current response independent of speed, and find out what happens to a speed loop when its current command saturates.
:::

::: predict
## The speed loop's PI controller asks for more current than the 100 A limit while the motor accelerates. What does its integrator do if nothing stops it?

- [ ] Nothing: the limit protects it
- [x] It keeps accumulating error during the whole current-limited ramp, so the speed overshoots badly before the integrator unwinds
- [ ] It resets to zero
- [ ] It makes the motor accelerate faster

::: reveal
While the output is clipped, the error stays large and the integrator keeps growing, though none of it reaches the motor. When the speed finally approaches the target, the stored integral holds the current high and the speed overshoots: 16.9% here, against 5.2% with conditional integration, which simply stops integrating while the output is clipped.
:::
:::

::: nameit
## The model

With $\omega = \frac{P}{2}\omega_m$:

$$L_d\frac{di_d}{dt} = v_d - Ri_d + \omega L_qi_q, \qquad L_q\frac{di_q}{dt} = v_q - Ri_q - \omega(L_di_d + \lambda_m)$$

$$J\frac{d\omega_m}{dt} = \tfrac{3}{2}\tfrac{P}{2}\left[\lambda_mi_q + (L_d - L_q)i_di_q\right] - T_L - B\omega_m$$

## Current control

PI regulators with $K_p = \omega_cL$ and $K_i = \omega_cR$ cancel each axis's electrical pole $R/L$, leaving a first-order closed loop of bandwidth $\omega_c$. Adding the **decoupling** terms $-\omega L_qi_q$ to $v_d$ and $+\omega(L_di_d + \lambda_m)$ to $v_q$ cancels the speed voltages, so the two axes become independent and identical at any speed.

## Speed control

With the current loop fast enough to treat as ideal, the mechanical plant is $K_t/(Js + B)$ with $K_t = \frac{3}{2}\frac{P}{2}\lambda_m$. A PI with $K_p = \omega_bJ/K_t$ sets a bandwidth near $\omega_b$, and its zero at $\omega_b/5$ removes steady-state error under load. The current command is clipped to $\pm I_\max$, and **conditional integration** freezes the integrator while it's clipped.
:::

::: example
## What does the current step give, for a 50 A command with $\omega_c$ = 2π × 500 rad/s?

::: solution
1. **Controller gains.**
   $$\begin{aligned} K_p &= 2\pi \times 500 \times 0.5\ \text{mH} \\ &= 1.571\ \text{V/A} \\ K_i &= 2\pi \times 500 \times 0.05 \\ &= 157.1\ \text{V/(A·s)} \end{aligned}$$
2. **q current.** It rises as $50(1 - e^{-\omega_ct})$: 31.6 A at one time constant (0.318 ms), 49.91 A after 2 ms, identically at standstill and at 200 rad/s, with $i_d$ staying at zero.
3. **Torque.** The torque follows: 0.6 N·m per ampere, 30 N·m at 50 A.

**Answer:** with $K_p$ = 1.571 V/A and $K_i$ = 157.1 V/(A·s), the q current rises to 50 A with a 0.318 ms time constant (31.6 A at one time constant, 49.91 A after 2 ms), making 30 N·m.
:::
:::

::: example
## What does the speed step to 1000 rpm look like with a 100 A limit?

::: solution
1. **Torque and acceleration at the limit.** $K_t$ = 0.6 N·m/A, so 100 A gives 60 N·m and an acceleration of 6000 rad/s² on 0.01 kg·m².
2. **The ramp.** The motor ramps at the limit to 90% of 104.7 rad/s in 19.4 ms (15.7 ms if it held full current all the way; the controller starts backing off as it nears the target).
3. **Overshoot and settling.** With conditional integration it overshoots by 5.2% and settles to within 0.01% by 0.3 s.
4. **Without anti-windup.** The overshoot is 16.9%.

**Answer:** a current-limited ramp at 6000 rad/s² that reaches 90% of 1000 rpm in 19.4 ms, overshoots by 5.2% and settles within 0.01% by 0.3 s (16.9% overshoot without anti-windup).
:::
:::

::: check
kind: python

## Step 1. Write `derivs(x, vd, vq, TL)`: the motor in the rotor frame.

```python starter
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def derivs(x, vd, vq, TL):
    # x = np.array([i_d, i_q, w_m]) with w_m the mechanical speed in rad/s. Return the time
    # derivatives as an np.array, from the dq voltage equations (electrical speed w = P/2 * w_m)
    # and J dw_m/dt = T - TL - B w_m with T = 1.5 (P/2) (LAM i_q + (LD - LQ) i_d i_q).
    return np.zeros(3)

print(derivs(np.array([0.0, 10.0, 50.0]), 0.0, 25.0, 1.0))
```

```python solution
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def derivs(x, vd, vq, TL):
    i_d, i_q, wm = x
    w = P/2*wm
    T = 1.5*P/2*(LAM*i_q + (LD - LQ)*i_d*i_q)
    return np.array([(vd - R*i_d + w*LQ*i_q)/LD,
                     (vq - R*i_q - w*(LD*i_d + LAM))/LQ,
                     (T - TL - B*wm)/J])

print(derivs(np.array([0.0, 10.0, 50.0]), 0.0, 25.0, 1.0))
```

```python tests
d = derivs(np.array([0.0, 10.0, 50.0]), 0.0, 25.0, 1.0)
want = np.array([200*0.5e-3*10/0.5e-3, (25 - 0.5 - 200*0.1)/0.5e-3, (6*0.1*10 - 1 - 0.05)/0.01])
assert np.allclose(d, want, rtol=1e-12), f"At i_q = 10 A, 50 rad/s, v_q = 25 V: derivatives {want}; got {d}."
d = derivs(np.array([-20.0, 30.0, -10.0]), 5.0, -3.0, 0.0)
w = -40.0
want = np.array([(5 + 0.05*20 + w*0.5e-3*30)/0.5e-3, (-3 - 0.05*30 - w*(0.5e-3*(-20) + 0.1))/0.5e-3, (6*0.1*30 + 0.001*10)/0.01])
assert np.allclose(d, want, rtol=1e-12), f"With negative i_d and reverse speed the cross-coupling terms must change sign correctly: want {want}, got {d}."
```

::: right
Right. Your model has the speed voltages and cross-coupling terms with the right signs.
:::
:::

::: check
kind: python

## Step 2. Write `current_step(iq_ref, wm)`: PI current loops with decoupling.

```python starter
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def current_step(iq_ref, wm, wc=2*np.pi*500, t_end=2e-3, h=1e-6):
    # Hold the rotor at mechanical speed wm and step the q-axis current command to iq_ref (d-axis
    # command 0). PI regulators on each axis, Kp = wc*L and Ki = wc*R, with decoupling:
    #   v_d = Kp*e_d + z_d - w*LQ*i_q,   v_q = Kp*e_q + z_q + w*(LD*i_d + LAM)
    # where z_d, z_q are the integrator states (dz/dt = Ki*e). Integrate the state
    # [i_d, i_q, z_d, z_q] from zero with rk4 at step h. Return (t, states) as numpy arrays,
    # states with shape (steps + 1, 4).
    n = int(round(t_end/h))
    return np.arange(n + 1)*h, np.zeros((n + 1, 4))

t, s = current_step(50.0, 200.0)
print(s[-1])
```

```python solution
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def current_step(iq_ref, wm, wc=2*np.pi*500, t_end=2e-3, h=1e-6):
    Kpd, Kid, Kpq, Kiq = wc*LD, wc*R, wc*LQ, wc*R
    w = P/2*wm
    def f(s):
        i_d, i_q, zd, zq = s
        ed, eq = -i_d, iq_ref - i_q
        vd = Kpd*ed + zd - w*LQ*i_q
        vq = Kpq*eq + zq + w*(LD*i_d + LAM)
        return np.array([(vd - R*i_d + w*LQ*i_q)/LD, (vq - R*i_q - w*(LD*i_d + LAM))/LQ, Kid*ed, Kiq*eq])
    n = int(round(t_end/h))
    out = np.zeros((n + 1, 4))
    s = np.zeros(4)
    for k in range(n):
        s = rk4(f, s, h)
        out[k + 1] = s
    return np.arange(n + 1)*h, out

t, s = current_step(50.0, 200.0)
print(s[-1])
```

```python tests
t, s = current_step(50.0, 200.0)
k = int(round(1/(2*np.pi*500)/1e-6))
assert s.shape == (2001, 4), f"Return 2001 states of 4 values; got shape {s.shape}."
assert abs(s[k, 1] - 50*(1 - np.exp(-t[k]*2*np.pi*500))) < 0.02, f"With pole-zero cancellation the q current rises as a first-order lag with bandwidth wc: at t = {t[k]*1e3:.3f} ms it should be {50*(1 - np.exp(-t[k]*2*np.pi*500)):.3f} A; got {s[k, 1]:.3f} A."
assert np.max(np.abs(s[:, 0])) < 1e-9, f"Decoupling should keep i_d at zero; it reached {np.max(np.abs(s[:, 0])):.3e} A."
t0, s0 = current_step(50.0, 0.0)
assert np.max(np.abs(s0[:, 1] - s[:, 1])) < 1e-9, "With exact decoupling the q-current response is the same at any speed; yours differs between 0 and 200 rad/s."
assert abs(s[-1, 1] - 50*(1 - np.exp(-2e-3*2*np.pi*500))) < 0.01, f"After 2 ms the q current should be {50*(1 - np.exp(-2e-3*2*np.pi*500)):.3f} A; got {s[-1, 1]:.3f}."
```

::: right
Right. A clean first-order current response, the same at every speed, with the d current untouched.
:::
:::

::: check
kind: python

## Step 3. Write `speed_step(n_ref)`: a current-limited speed loop with anti-windup.

```python starter
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def speed_step(n_ref, anti_windup=True, Imax=100.0, wb=2*np.pi*20, t_end=0.3, h=1e-5, TL=0.0):
    # Speed loop around an ideal current loop (i_q follows its command instantly).
    # Kt = 1.5*(P/2)*LAM, Kp = wb*J/Kt, Ki = Kp*wb/5. Each step, in this order:
    #   e = w_ref - w_m;  u = Kp*e + z;  i_q = u clipped to [-Imax, Imax];
    #   if not anti_windup or i_q == u: z += Ki*e*h   (conditional integration)
    #   advance w_m one step with rk4 on J dw/dt = Kt*i_q - TL - B*w.
    # Start from rest with z = 0. Return (t, w_m, i_q) arrays of length steps + 1
    # (i_q[0] = 0).
    n = int(round(t_end/h))
    return np.arange(n + 1)*h, np.zeros(n + 1), np.zeros(n + 1)

t, w, iq = speed_step(1000)
print(w[-1], w.max())
```

```python solution
import numpy as np

# An 8-pole surface permanent-magnet motor.
P, R, LD, LQ, LAM = 8, 0.05, 0.5e-3, 0.5e-3, 0.1    # poles, ohms, henries, henries, webers
J, B = 0.01, 0.001                                  # kg·m², N·m·s/rad

def rk4(f, x, h):
    k1 = f(x); k2 = f(x + h/2*k1); k3 = f(x + h/2*k2); k4 = f(x + h*k3)
    return x + h/6*(k1 + 2*k2 + 2*k3 + k4)

def speed_step(n_ref, anti_windup=True, Imax=100.0, wb=2*np.pi*20, t_end=0.3, h=1e-5, TL=0.0):
    Kt = 1.5*P/2*LAM
    Kp = wb*J/Kt
    Ki = Kp*wb/5
    w_ref = n_ref*2*np.pi/60
    n = int(round(t_end/h))
    ws, iqs = np.zeros(n + 1), np.zeros(n + 1)
    wm, z = 0.0, 0.0
    for k in range(n):
        e = w_ref - wm
        u = Kp*e + z
        iq = min(max(u, -Imax), Imax)
        if not anti_windup or iq == u:
            z += Ki*e*h
        f = lambda w: (Kt*iq - TL - B*w)/J
        k1 = f(wm); k2 = f(wm + h/2*k1); k3 = f(wm + h/2*k2); k4 = f(wm + h*k3)
        wm += h/6*(k1 + 2*k2 + 2*k3 + k4)
        ws[k + 1], iqs[k + 1] = wm, iq
    return np.arange(n + 1)*h, ws, iqs

t, w, iq = speed_step(1000)
print(w[-1], w.max())
```

```python tests
w_ref = 1000*2*np.pi/60
t, w, iq = speed_step(1000)
assert len(w) == 30001, f"Return 30001 samples; got {len(w)}."
assert np.max(np.abs(iq)) <= 100 + 1e-9, "The current command must never exceed Imax."
assert abs(w[-1]/w_ref - 1) < 1e-4, f"After 0.3 s the speed should have settled at {w_ref:.3f} rad/s; got {w[-1]:.3f}."
os_aw = w.max()/w_ref - 1
assert abs(os_aw - 0.05244) < 5e-4, f"With conditional integration the overshoot should be 5.24%; got {100*os_aw:.2f}%."
t90 = t[np.argmax(w >= 0.9*w_ref)]
assert abs(t90 - 0.01943) < 2e-4, f"The speed should reach 90% at 19.4 ms (the current limit sets the acceleration); got {1e3*t90:.2f} ms."
t, w2, iq2 = speed_step(1000, anti_windup=False)
os_nw = w2.max()/w_ref - 1
assert abs(os_nw - 0.16913) < 5e-4, f"Without anti-windup the integrator charges up during the current-limited ramp and the overshoot grows to 16.9%; got {100*os_nw:.2f}%."
```

::: right
Right. Conditional integration keeps the overshoot to 5% where a plain PI gives 17%.
:::
:::

::: explain
## Why do the decoupling terms make the current loop's response the same at every speed?

::: model
In the rotor frame each axis's voltage equation contains a term from the other axis: the d equation has $+\omega L_qi_q$ and the q equation has $-\omega(L_di_d + \lambda_m)$. These speed voltages grow with speed and couple the axes, so without help a change in $i_q$ disturbs $i_d$ and the back-EMF $\omega\lambda_m$ acts as a disturbance the q-axis PI must fight. The decoupling terms add exactly the opposite voltages to the controller's outputs, computed from the measured currents and speed. They cancel the coupling and the back-EMF inside the motor, leaving each axis as a plain R–L circuit driven by its own PI controller. Since that circuit doesn't depend on speed, neither does the closed-loop response.
:::
:::

::: practice

::: check
given: w = 300 | 2000; L = 0.2 | 1; R = 0.02 | 0.2
answer: w*L*1e-3
unit: Ω
tolerance: 0.5%

## Current-loop gain $K_p$ for bandwidth {w} rad/s, L = {L} mH (R = {R} Ω)?

::: misses
- [any] $K_p = \omega_cL$.
:::
:::

::: check
given: P = 4 | 10; l = 0.05 | 0.2; I = 30 | 200; J = 0.002 | 0.05
answer: 1.5*P/2*l*I/J
unit: rad/s^2
tolerance: 0.5%

## Largest acceleration: {P} poles, $\lambda_m$ = {l} Wb, {I} A limit, J = {J} kg·m² (no load)?

::: misses
- [any] $K_tI_\max/J$.
:::
:::

::: check
given: w = 50 | 300; J = 0.002 | 0.05; P = 4 | 10; l = 0.05 | 0.2
answer: w*J/(1.5*P/2*l)
unit: A
tolerance: 0.5%

## Speed-loop $K_p$ (A per rad/s): bandwidth {w} rad/s, J = {J}, {P} poles, $\lambda_m$ = {l} Wb?

::: misses
- [any] $\omega_bJ/K_t$.
:::
:::
:::
