# Timing inside a digitally controlled converter: from PWM counter to duty update

An analog controller reacts the instant the output moves. A digital one cannot. It has to wait for the next sample, convert it, run the interrupt, compute a new duty cycle, and then wait again until the PWM timer is willing to use that duty. Every step takes time, and the steps happen in a fixed order inside each switching period.

This post follows that order step by step on a real example: a 48 V to 12 V buck at 100 kHz with a Type III voltage loop, run in Voltecx with the timing of a microcontroller. You will see where the delay comes from, why it is usually one to one and a half switching periods, how much phase margin it eats, and what goes wrong when the interrupt runs late or the PWM is too coarse.

It is about **timing**: what happens when, and in what order. For how a PWM signal is made, see [PWM explained](https://voltecx-web.nguyenvanqui291.workers.dev/blog/pwm-explained); for how and where to sample, see [ADC sampling in power converters](https://voltecx-web.nguyenvanqui291.workers.dev/blog/adc-sampling-power-converters).

## The picture: a photo, a calculation and a mailbox

Think of the controller as three people in a relay.

1. **The photographer** (the ADC) takes a snapshot of the output voltage at a fixed moment in each period. Whatever happens between snapshots, the controller does not see.
2. **The calculator** (the interrupt service routine, ISR) takes the photo, works out the new duty cycle and writes it down. This takes a few microseconds.
3. **The mailbox** (the PWM's shadow register) accepts the note at any time, but the postman (the PWM timer) only empties it once per period, at the start of the next one.

The output voltage only changes when the new duty reaches the switch. So the information in the photo arrives at the power stage after the photo, the calculation *and* the wait at the mailbox. That chain is the loop delay.

## The chain inside one switching period

Here is the order of events in a typical microcontroller (the same structure appears on most microcontrollers made for power conversion):

1. **The PWM counter counts.** In up/down (center-aligned) mode it counts from 0 to its period value and back. Plotted, it is a triangle: the *carrier*. The gate is on while the duty value is above the counter.
2. **The ADC is triggered at a fixed point of the counter**, usually the valley (counter = 0) or the peak. With a triangle carrier those are the middle of the on-time and the middle of the off-time, where the inductor current crosses its average and the switching noise is furthest away.
3. **The conversion runs.** The ADC needs a conversion time (see its data sheet) before the result is ready.
4. **The end of conversion raises an interrupt.** After the interrupt latency, the ISR starts.
5. **The ISR computes the new duty.** It reads the result, runs the compensator (a difference equation), limits the output and converts it to timer counts.
6. **The ISR writes the compare register.** With preload (shadow register) on, the value waits in a buffer.
7. **The timer copies the buffer into the active register at its update event**, usually the next counter valley. Only now does the gate edge move.

If you remember one thing: **the sample is taken at the start of period k, and the duty computed from it acts in period k + 1.**

## The timing diagram from a run

The figure below is not drawn by hand. It is two switching periods from a Voltecx run of the buck, zoomed on the moment a reference step arrives (the reference jumps from 12 V to 12.5 V at 3.003 ms, just after a sample). Time is in µs from the carrier peak at 3.005 ms; the vertical lines mark the sample at 5 µs, the end of the ISR at 7.94 µs and the next counter valley at 15 µs.

![Two switching periods of the digitally controlled buck in Voltecx: the triangle carrier with the duty in the shadow register and in a register written at the end of the ISR, the error and its sampled value, and the gate signal for each register.](https://voltecx-web.nguyenvanqui291.workers.dev/media/blog/digital-control-loop-timing/timing-diagram.svg)

How to read it, from top to bottom:

- **Panel 1, carrier and duty.** The triangle is the counter. The red line is the duty in the shadow register: it only changes at the valley at 15 µs. The green line is the same duty written into the register at the end of a 2.94 µs ISR: it changes at 7.94 µs.
- **Panel 2, error.** The error (blue) has been 0.5 V since the step at −2 µs, but the controller's sampled error (red) only jumps at the sample at 5 µs. The step was invisible for 7 µs.
- **Panels 3 and 4, gates.** With the shadow register, the first pulse after the sample is still the old, narrow one; the wider pulse starts at 13.75 µs. With the update at the end of the ISR, the wider pulse starts 1.35 µs earlier, at 12.4 µs.

Notice the gate edges: with a triangle carrier, the gate turns on where the falling carrier crosses the duty and turns off where the rising carrier crosses it. A duty written in the middle of a period changes only the edges that are still to come.

## Immediate update or shadow register?

Most PWM timers let you choose when a new compare value takes effect.

| | Shadow register (update at period start) | Immediate update (at the end of the ISR) |
|---|---|---|
| When the duty acts | Next counter valley | As soon as it is written |
| Delay from sample | One full period | ISR time only |
| Pulse shape | Always symmetric | Can be asymmetric for one period |
| Risk | None from the update itself | A value written just after the counter passed it can skip or add an edge |
| Typical use | The default; safest | Fast loops, when the ISR is short and its timing is known |

The immediate update is faster, but it is a race: if the ISR writes a new value just after the counter has passed it, that period loses its edge (a missed pulse) or gets one too many. That is why the shadow register is the default and why firmware that uses immediate update usually limits how far the duty can move in one step.

## Adding up the delay

The delay the loop sees has two parts.

- **The computation delay** $t_c$: from the sample to the moment the new duty is in the active register. With a shadow register that is one sample period $T_s$; with an immediate update it is the ISR time.
- **The modulator delay**: the duty acts over the whole period, not at one instant. Averaged, a duty that is held for a period acts about half a period late. This is the same half sample that a zero-order hold costs (Franklin, Powell and Workman, *Digital Control of Dynamic Systems*, §6.3).

So the total loop delay is

$$T_d = t_c + \frac{T_s}{2}$$

| Timing scheme | $t_c$ | $T_d$ |
|---|---|---|
| Ideal, no computation | 0 | 0.5 $T_s$ |
| ISR of 2.94 µs, update at its end ($T_s$ = 10 µs) | 0.294 $T_s$ | 0.79 $T_s$ |
| Shadow register, update at the next period (the usual case) | 1 $T_s$ | 1.5 $T_s$ |
| Calculation that needs two periods | 2 $T_s$ | 2.5 $T_s$ |

That is where the rule of thumb "a digital loop has one to one and a half periods of delay" comes from (D. G. Holmes and T. A. Lipo, *Pulse Width Modulation for Power Converters*, ch. 4, on regular-sampled PWM; S. Buso and P. Mattavelli, *Digital Control in Power Electronics*).

## Why the delay matters: phase lag

A pure delay does not change the gain of the loop at all. It only shifts the phase, and the shift grows with frequency:

$$\varphi_{delay} = 360° \cdot f \cdot T_d$$

At the crossover frequency $f_c$, every degree of that lag comes straight out of the phase margin. A delay is like talking to someone on a satellite phone: each of you waits for the other, and if you both react too quickly you keep talking over each other. The faster you want the conversation (the higher $f_c$), the more the delay hurts.

### Worked example

The buck is the `buckClosedLoop` example: 48 V in, 12 V out, 5 A, 100 kHz, 100 µH and 100 µF. `design.voltageLoop` gives it a Type III compensator that crosses at $f_c$ = 5.78 kHz with 60° of phase margin, already counting the half period of the modulator. The sample period is $T_s$ = 10 µs.

Each extra sample of computation costs

$$360° \times 5.78\ \text{kHz} \times 10\ \mu\text{s} = 20.8°$$

| Computation delay | Total $T_d$ | Phase margin | Gain margin |
|---|---|---|---|
| 0 | 0.5 $T_s$ | 60° | 12.2 dB |
| 0.5 $T_s$ | 1 $T_s$ | 49.6° | 8.9 dB |
| 1 $T_s$ (shadow register) | 1.5 $T_s$ | 39.2° | 6.4 dB |
| 2 $T_s$ | 2.5 $T_s$ | 18.4° | 2.6 dB |

`design.digitalize` reads the loop gain of the discretized compensator with each delay; its phase margin lies exactly on the straight line $60° - 20.8°$ per sample. The gain margin falls too, because the extra phase lag moves the −180° crossing down to where the loop gain is higher.

![Phase margin (from design.digitalize and from 60° − 20.8° per sample) and gain margin of the buck's Type III loop against the computation delay in samples.](https://voltecx-web.nguyenvanqui291.workers.dev/media/blog/digital-control-loop-timing/phase-margin-vs-delay.svg)

A loop designed in the s-domain for 60° and then put into firmware with the usual shadow register ends up with 39°. If you designed for 45° (a common target), you would be at about 24°.

## What the delay looks like in the time domain

Phase margin is abstract; overshoot is not. The figure below is the same 0.5 V reference step simulated four times, with 0, 0.5, 1 and 2 samples of computation (the duty loaded as soon as it is ready).

![Output voltage of the buck in Voltecx for a 12 V to 12.5 V reference step with a total loop delay of 0.5, 1, 1.5 and 2.5 switching periods.](https://voltecx-web.nguyenvanqui291.workers.dev/media/blog/digital-control-loop-timing/step-response-delay.svg)

| Total delay $T_d$ | Phase margin | Simulated overshoot |
|---|---|---|
| 0.5 $T_s$ | 60° | 4.5 % |
| 1 $T_s$ | 49.6° | 15.7 % |
| 1.5 $T_s$ | 39.2° | 30 % |
| 2.5 $T_s$ | 18.4° | 66 % |

The shadow register (one sample, loaded at the valley) gives the same 30 % as the 1.5 $T_s$ case, as it should. At 2.5 $T_s$ the output rings for several cycles: the loop is close to oscillating.

The slow approach to 12.5 V after the first peak, in all four curves, is not caused by the delay. It comes from the two compensator zeros at 676 Hz, far below the crossover, which the integrator needs some time to settle against.

## Single update or double update?

With a triangle carrier you can sample and update twice per period: at the valley and at the peak. The ISR then runs at 200 kHz, and with one sample of computation the delay halves:

$$T_d = 1.5 \times 5\ \mu\text{s} = 7.5\ \mu\text{s} \quad\text{instead of}\quad 1.5 \times 10\ \mu\text{s} = 15\ \mu\text{s}$$

For the buck, `design.digitalize` at a 200 kHz sample rate gives 54.8° instead of 39.2°, and the simulated overshoot drops from 30 % to 8.1 %.

The price:

- **Twice the CPU load.** The ISR must fit into half the time.
- **Both sample points must be clean.** The peak is the middle of the off-time, which is fine for a buck's inductor current but may be close to another converter's switching edge in an interleaved design.
- **Asymmetric pulses.** The on-time is now built from two halves computed at different times, which is fine for control but makes the pulse no longer centered.

## When the calculation is late

The ISR has a time budget: it must finish within one sample period, with margin for other interrupts. The *CPU load* of the control ISR is $t_{ISR}/T_s$.

In Voltecx the `mcu` block models the ISR time. Each ISR starts at its sample instant, or when the previous one returns if that is later. If an ISR cannot even start before the next instant, its sample is lost, as an interrupt controller keeps only one interrupt pending.

The figure compares an ISR of 2.94 µs (29 % load) with one of 10.6 µs (106 % load), both writing the duty at their end.

![The duty register and the output voltage of the buck in Voltecx for an ISR taking 29 % and 106 % of the 10 µs period; the vertical lines are the sample instants.](https://voltecx-web.nguyenvanqui291.workers.dev/media/blog/digital-control-loop-timing/late-isr.svg)

What happens with the late ISR:

- Each ISR starts 0.6 µs later than the one before, so the duty updates every 10.6 µs instead of every 10 µs. They drift against the sample instants (the vertical lines).
- Once the lag reaches a whole period, one sample is dropped and the drift starts over: about one sample in $10/0.6 \approx 17$ is lost.
- The delay grows from period to period, so the loop sees a delay that changes over time (jitter), and on average a much longer one. The overshoot rises from 15.6 % to 72.5 %.
- The `overrun` output of the block goes to 1 and its `load` output reads 1.06.

On real hardware the symptoms are the same: an output that rings more than the design says, an audible or visible subharmonic, and a converter that gets worse when you add a feature to the ISR.

## Limit cycles from PWM resolution

The last timing effect is about *steps* rather than delays. A PWM timer can only set the duty in whole counts. At 100 kHz with a 100 MHz timer clock there are 1000 counts per period, so the duty moves in steps of 0.1 %. In the buck, one step moves the output by

$$\Delta V_{DPWM} = V_{in} \cdot \frac{1}{1000} = 48\ \text{mV}$$

A 12-bit ADC over 0 to 16 V resolves $16/4096 = 3.9$ mV. The controller can see a 3.9 mV error but can only correct in 48 mV steps. It can never land exactly on the set point, so it hunts between duty levels forever: a **limit cycle**.

The condition to avoid it (A. V. Peterchev and S. R. Sanders, "Quantization resolution and limit cycling in digitally controlled PWM converters", IEEE Trans. Power Electron. 18(1), 2003) is that one DPWM step must move the output less than one ADC step, and that the loop has integral action. With the 184 ps high-resolution step of the STM32G474 timer (ST RM0440), one step moves the output 0.88 mV, a quarter of an ADC step.

![The sampled error and the duty register of the buck in Voltecx in steady state, with a 1000-count PWM timer and with a 184 ps high-resolution PWM step.](https://voltecx-web.nguyenvanqui291.workers.dev/media/blog/digital-control-loop-timing/limit-cycle.svg)

With 1000 counts the duty never rests: it hops over five counts (0.258 to 0.263) and the sampled error jumps by ±1 ADC step. With the 184 ps step, the loop settles on one ADC code and both lines stay flat. [Tutorial 7](https://voltecx-web.nguyenvanqui291.workers.dev/docs/tutorials/07-digital-control) walks through the same check in `design.digitalize`, with the fix.

## Common mistakes

- **Designing the analog loop with no delay and adding firmware later.** Plan for $T_d$ = 1.5 $T_s$ from the start, or design directly with the delay in the loop.
- **Pushing the crossover too close to the switching frequency.** With $T_d$ = 1.5 $T_s$, a crossover at $f_s/10$ already costs 54° of phase, more than most loops can spare. Keep the crossover well below that, or shorten the delay.
- **Triggering the ADC after the ISR instant and still counting a full sample of delay.** If the sample is taken *after* the interrupt starts (an ADC trigger offset), the controller reads the previous sample, and the latency is already one period. Counting another sample on top makes it two.
- **Forgetting the ISR's worst case.** Measure the longest path, with every branch and other interrupts that can preempt the ISR. The average does not matter; the worst case does.
- **Using immediate update without thinking about edges.** A compare value written just after the counter passed it skips an edge for that period.
- **A PWM coarser than the ADC.** If $V_{in}/N_{counts}$ is larger than one ADC step, expect a limit cycle. Use high-resolution PWM, dithering or a coarser ADC reading in the integrator.
- **Measuring the delay in the wrong units.** The delay that matters is in seconds against the crossover frequency, not in "cycles". One period at 20 kHz is five times worse than one period at 100 kHz for the same crossover.

## A timing budget, step by step

1. Pick the switching frequency and the sample rate (single or double update).
2. Pick where the ADC samples (valley, peak) and check that it is away from switching edges.
3. Measure or estimate the worst-case ISR time, including the conversion time and interrupt latency.
4. Decide on shadow register or immediate update, and compute $T_d = t_c + T_s/2$.
5. Compute the phase lag at your crossover, $360° \cdot f_c \cdot T_d$, and design the compensator with it.
6. Check the CPU load, $t_{ISR}/T_s$, with margin for everything else the processor does.
7. Check the PWM resolution against the ADC resolution.
8. Simulate the loop with the real timing and look at the step response.

## Try it in Voltecx

- The **`mcu` block** models the timing of the microcontroller between the controller and the PWM: `fs` (ISR rate), `fpwm`, `align` (`start` for an ISR at the carrier valley, or `peak`), `delay` (computation delay in samples) or `tIsr` / `cycles` and `fclk` (the ISR time), `update` (`period` for the shadow register, `immediate` or `end`), and `counts` or `bits` for the duty resolution. Its `load` and `overrun` outputs show the CPU load.
- The **`zoh`** block samples a signal, and **`ztf`**, **`dpi`** and **`dpid`** run discrete controllers at the same instants. The `pwm` block's `counts` and `hrpwm` round the duty like a real timer.
- **`design.digitalize`** turns a `design.voltageLoop` compensator into a difference equation and reads the loop again with the computation delay, the ISR time and the update mode, the coefficient rounding and the limit-cycle check. It reports the phase margin lost.
- [Tutorial 7](https://voltecx-web.nguyenvanqui291.workers.dev/docs/tutorials/07-digital-control) goes through the whole flow, and **Tools › Code Generation** writes the C of the control blocks; see [code generation](https://voltecx-web.nguyenvanqui291.workers.dev/features/code-generation).
- To see your own timing diagram, record the carrier, the `mcu` block's duty output and the gate, and zoom on two periods after a step.
