---
title: PWM and sigma-delta outputs
heading: Making an analog level from a counter, a comparator or an accumulator, and how fast its ripple dies
eyebrow: C7 · Lesson 30 · PWM and sigma-delta outputs
xp: 40
---

::: hook
Digital chips have plenty of pins that can only be 0 or 1, yet they dim LEDs smoothly, set motor speeds and even play audio. The trick is to switch fast and let something slow average it: an RC filter, a motor's inductance, an eye. A counter and a comparator from lesson 29 make **pulse-width modulation**, whose average is the fraction of each period spent high. An adder and a register make a **sigma-delta** bitstream with the same average but its 1s spread out as evenly as possible, which pushes the ripple to much higher frequencies where a filter removes it easily.
:::

::: play
- A first-order sigma-delta modulator built from a 3-bit accumulator. On each clock it adds the input X (0 to 7) to the accumulator, and the carry out of that addition is the output bit.
- With X = 2 (binary 010), the output is 1 on one clock in every four: an average of 2/8. Change X and watch the density of 1s follow it, always as evenly spread as the clock allows.
:::

```sim logic
input X2, X1, X0
output OUT
clock CLK 4
set X1 = 1
assign s0 = A0 ^ X0
assign c1 = A0 & X0
assign s1 = A1 ^ X1 ^ c1
assign c2 = A1 & X1 | (A1 ^ X1) & c1
assign s2 = A2 ^ X2 ^ c2
assign OUT = A2 & X2 | (A2 ^ X2) & c2
always @(posedge CLK) begin A0 <= s0; A1 <= s1; A2 <= s2; end
wave: CLK, OUT, A2, A1, A0
time: 72
```

::: predict
## An 8-bit PWM and an 8-bit sigma-delta modulator both run from a 16 MHz clock with an input of 64 (a quarter of full scale), and both feed the same RC filter. How do their ripples compare?

- [ ] They're the same, since the averages are the same
- [x] The sigma-delta's is about 64 times smaller
- [ ] The PWM's is smaller
- [ ] The sigma-delta's is about 4 times smaller

::: reveal
The PWM repeats every 256 clocks: one 64-clock pulse per period, at 62.5 kHz. The sigma-delta puts out a 1 every 4 clocks, a 4 MHz pattern. Through an RC filter much slower than both, ripple scales with the pattern's period, so the sigma-delta's is 256/4 = 64 times smaller. Near codes that don't divide evenly, its pattern is longer and the advantage shrinks, but it never does worse than the PWM.
:::
:::

::: nameit
## Pulse-width modulation

An $N$-bit counter counts from 0 to $2^N - 1$ and wraps; a comparator sets the output high while the count is below the input code $k$. The duty cycle is $D = k/2^N$, the frequency is

$$f_{PWM} = \frac{f_{clk}}{2^N}$$

and the average output is $DV_{DD}$, with steps of $V_{DD}/2^N$. Resolution and frequency trade off: each extra bit halves the PWM frequency.

## Filtering and ripple

An RC low-pass with $RC \gg T$ passes the average and shrinks the ripple. During the high time $DT$, the capacitor charges with current about $(V - DV)/R$, so the peak-to-peak ripple is

$$\Delta V \approx \frac{V\,D(1 - D)\,T}{RC}$$

largest at 50% duty. Higher frequency or a slower filter reduces it; a slower filter also slows the response to a new code, with time constant $RC$.

## First-order sigma-delta

Replace the counter with an accumulator: every clock, add $k$ to an $N$-bit register and output the carry. The carries come at an average rate $k/2^N$, the same as the PWM's duty, but spread as evenly as possible: the 1s and 0s alternate as often as the code allows. For $k = 2^N/m$, the pattern repeats every $m$ clocks, so the ripple is $m/2^N$ times the PWM's. This is the same idea as the delta-sigma converters of signal processing, here in its simplest form: the accumulator keeps the running error, and the output corrects it on every clock.

The catch: many more edges per second, which cost switching power and, on a long trace or a driver with slow edges, add error from unequal rise and fall times. PWM is usually preferred for power stages, sigma-delta for references and audio.
:::

::: example
## A 16 MHz microcontroller makes PWM with an 8-bit and a 10-bit counter. What are the PWM frequency and voltage step for each on 3.3 V?

::: solution
1. **8-bit counter.** The PWM frequency and the voltage step are
   $$\begin{aligned} \frac{16\ \text{MHz}}{256} &= 62.5\ \text{kHz} \\ \frac{3.3\ \text{V}}{256} &= 12.9\ \text{mV} \end{aligned}$$
2. **10-bit counter.**
   $$\begin{aligned} \frac{16\ \text{MHz}}{1024} &= 15.6\ \text{kHz} \\ \frac{3.3\ \text{V}}{1024} &= 3.2\ \text{mV} \end{aligned}$$
3. **The trade-off.** Four times the resolution costs four times the period, and so, for the same filter, four times the ripple.

**Answer:** 62.5 kHz with 12.9 mV steps for 8 bits, and 15.6 kHz with 3.2 mV steps for 10 bits.
:::
:::

::: example
## The 8-bit PWM (3.3 V, 62.5 kHz) feeds an RC filter with $RC$ = 1 ms. Find the worst-case ripple, and the time constant needed to bring it under one LSB.

::: solution
1. **Worst-case ripple.** At $D$ = 0.5, with $T$ = 16 µs:
   $$\begin{aligned} \Delta V &\approx \frac{3.3 \times 0.25 \times 16\ \mu\text{s}}{1\ \text{ms}} \\ &= 13.2\ \text{mV} \end{aligned}$$
   about one LSB (12.9 mV) already.
2. **A quarter LSB.** Getting comfortably below, say to a quarter LSB, needs $RC$ of about 4 ms.
3. **The cost.** That makes the output take about $5RC$ = 20 ms to settle after a change, the PWM digital-to-analog converter's basic trade-off.

**Answer:** about 13.2 mV, one LSB; a quarter LSB needs $RC$ of about 4 ms, which takes about 20 ms to settle.
:::
:::

::: example
## An 8-bit sigma-delta modulator at 16 MHz is given $k$ = 64 and feeds the same 1 ms filter. What pattern does it produce, and what ripple?

::: solution
1. **The pattern.** Adding 64 each clock to an 8-bit accumulator carries every fourth clock: 0001 repeating, a 4 MHz pattern whose high time is one clock, 62.5 ns.
2. **Its ripple.**
   $$\begin{aligned} \Delta V &\approx 3.3 \times 0.25 \times 0.75 \\ &\quad \times \frac{4 \times 62.5\ \text{ns}}{1\ \text{ms}} \\ &= 0.155\ \text{mV} \end{aligned}$$
3. **The PWM at the same code.**
   $$\begin{aligned} \Delta V &\approx \frac{3.3 \times 0.1875 \times 16\ \mu\text{s}}{1\ \text{ms}} \\ &= 9.9\ \text{mV} \end{aligned}$$
4. **Compare.** The sigma-delta ripple is 64 times less, so the filter could be 64 times faster for the same ripple.

**Answer:** 0001 repeating at 4 MHz, with about 0.155 mV of ripple, 64 times less than the PWM's 9.9 mV.
:::
:::

::: check
given: f = 8 | 16 | 48 | 100; N = 8 | 10 | 12
answer: f*1e3/2^N
unit: kHz
tolerance: 0.5%

## A PWM generator runs its {N}-bit counter from a {f} MHz clock. What is the PWM frequency, in kHz?

::: right
Right. $f_{clk}/2^N$ = {answer}.
:::

::: misses
- [f*1e3/N] The counter has $2^N$ states, not $N$.
- [any] Not yet. One period is $2^N$ clocks.
:::
:::

::: check
given: V = 3.3 | 5; D = 0.2 | 0.3 | 0.7 | 0.9; f = 2 | 20 | 62.5; RC = 0.5 | 2 | 10
answer: V*D*(1 - D)/(f*1e3)/(RC*1e-3)*1e3
unit: mV
tolerance: 1%

## A {V} V PWM at {f} kHz and duty {D} drives an RC filter with $RC$ = {RC} ms. What's the peak-to-peak ripple, in mV?

::: right
Right. $VD(1 - D)T/RC$ = {answer}.
:::

::: misses
- [V*D/(f*1e3)/(RC*1e-3)*1e3] Include the $(1 - D)$: the ripple vanishes at 0 and 100% duty.
- [V*0.25/(f*1e3)/(RC*1e-3)*1e3] That's the worst case at 50%. Use this duty.
- [any] Not yet. $\Delta V \approx VD(1 - D)T/RC$.
:::
:::

::: check
given: V = 3.3 | 5; N = 8 | 10; f = 16 | 64; q = 0.25 | 0.5 | 1
answer: V*0.25*(2^N/(f*1e6))/(q*V/2^N)*1e3
unit: ms
tolerance: 1%

## A {V} V, {N}-bit PWM from a {f} MHz clock must have at most {q} LSB of ripple at its worst duty. What filter time constant does it need?

::: right
Right. Set $V/4 \cdot T/RC$ equal to $qV/2^N$: $RC$ = {answer}.
:::

::: misses
- [V*(2^N/(f*1e6))/(q*V/2^N)*1e3] The worst case is $D(1 - D) = \tfrac14$.
- [any] Not yet. $RC = \frac{V \cdot 0.25 \cdot T}{q \cdot V/2^N}$, with $T = 2^N/f_{clk}$.
:::
:::

::: check
given: N = 8 | 10 | 12; m = 4 | 8 | 128
answer: 2^N/m
tolerance: 0.5%

## An {N}-bit first-order sigma-delta should output a 1 once every {m} clocks. What input code does that?

::: right
Right. The density of 1s is $k/2^N$, so $k = 2^N/m$ = {answer}.
:::

::: misses
- [m] The density is $k/2^N$; solve for k.
- [2^N - 2^N/m] That gives 1s on all but one clock in {m}.
- [any] Not yet. $k/2^N = 1/m$.
:::
:::

::: check
given: N = 8 | 10; m = 4 | 8 | 32
answer: m/2^N
tolerance: 0.5%

## For an {N}-bit code $k = 2^{\given{N}}/\given{m}$, by what factor is the sigma-delta's ripple smaller than the PWM's through the same slow filter? (Give the ratio of sigma-delta to PWM.)

::: right
Right. The patterns repeat every {m} and every $2^N$ clocks, so the ratio is $m/2^N$ = {answer}.
:::

::: misses
- [2^N/m] That's PWM over sigma-delta. The sigma-delta's ripple is the smaller one.
- [any] Not yet. Ripple scales with the pattern's period.
:::
:::

::: check
kind: choice

## A designer uses a sigma-delta output to drive the gate of a large power MOSFET switching a motor. Why might PWM be the better choice there?

- [x] The sigma-delta switches far more often, and each transition costs switching loss in the power stage
- [ ] Sigma-delta can't produce duty cycles above 50%
- [ ] PWM has finer resolution
- [ ] A motor can't average a sigma-delta stream

::: right
Right. Switching losses grow with the number of transitions per second. A power stage wants as few transitions as the ripple allows, which is PWM's strength; sigma-delta suits low-power outputs such as references and audio.
:::

::: misses
- [2] It covers the whole range from 0 to 1.
- [3] For the same counter width, both have $2^N$ levels.
- [4] The motor's inductance averages either one; the issue is loss in the switch.
:::
:::

::: check
kind: derivation
vars: V = 1..12, D = 0.05..0.95, T = 1e-6..1e-4, R = 1000..100000, C = 1e-8..1e-6

## Derive the PWM ripple through an RC filter with $RC \gg T$.

::: step
answer: (V - D*V)/R

### The capacitor sits near the average $DV$. What current flows into it while the output is high?
:::

::: step
answer: (V - D*V)/R*D*T/C

### It flows for $DT$. How much does the capacitor's voltage rise?
:::

::: right
Right. $\Delta V = VD(1 - D)T/RC$: the charge gained in the high part equals that lost in the low part.
:::
:::

::: check
kind: python
given: N = 6 | 8; k = 5 | 16 | 21

## Simulate both modulators through an RC filter. With an `N`-bit counter ({N}) and code `k` = {k}, build 64 periods' worth of bits ($64 \cdot 2^N$ clocks) for PWM (`1` while `count < k`) and for the sigma-delta (carry of an `N`-bit accumulator starting at 0). Filter each with the exact one-pole update `v = v + (b - v)*a` per clock, `a = 1 - exp(-1/50)` (RC = 50 clocks), starting from `v = k/2**N`. Over the last two PWM periods, set `pwm_pp` and `sd_pp` to the peak-to-peak values, and `ratio = sd_pp/pwm_pp`.

```python starter
import math
pwm_pp = sd_pp = 0.1
ratio = 1.0
```

```python solution
import math
M = 1 << N
n = 64 * M
a = 1 - math.exp(-1 / 50)
pwm = [1 if (i % M) < k else 0 for i in range(n)]
sd, acc = [], 0
for i in range(n):
    acc += k
    sd.append(acc >> N)
    acc &= M - 1
def pp(bits):
    v = k / M
    out = []
    for b in bits:
        v += (b - v) * a
        out.append(v)
    tail = out[-2 * M:]
    return max(tail) - min(tail)
pwm_pp, sd_pp = pp(pwm), pp(sd)
ratio = sd_pp / pwm_pp
```

```python tests
import math
M = 1 << N
n = 64 * M
a = 1 - math.exp(-1 / 50)
def run(bits):
    v = k / M; out = []
    for b in bits:
        v += (b - v) * a; out.append(v)
    t = out[-2 * M:]
    return max(t) - min(t)
p = run([1 if (i % M) < k else 0 for i in range(n)])
acc, s = 0, []
for i in range(n):
    acc += k; s.append(acc >> N); acc &= M - 1
q = run(s)
assert abs(pwm_pp - p) < 1e-12 and abs(sd_pp - q) < 1e-12, f"Expected pp ripples {p:.6g} (PWM) and {q:.6g} (sigma-delta)."
assert abs(ratio - q / p) < 1e-12 and ratio < 1, "The sigma-delta's ripple should be the smaller."
```

::: right
Right. The ratio is smallest for codes like 16 of 256 that divide evenly, and larger for awkward codes like 21, but the sigma-delta wins at every code.
:::
:::

::: explain
## Why does a sigma-delta bitstream have less ripple after a filter than PWM at the same average and clock rate, even though both contain the same number of 1s per $2^N$ clocks?

::: model
A low-pass filter removes high frequencies better than low ones, so what matters is where each bitstream puts its fluctuation. PWM gathers all the 1s of a period into one pulse, so its fluctuation repeats once per period, at $f_{clk}/2^N$, the lowest frequency available, and the filter's capacitor charges and discharges over a whole long pulse. The sigma-delta interleaves the 1s with the 0s as evenly as possible, so its pattern repeats much faster, often every few clocks, and the capacitor only moves a little before the bitstream reverses. Same average, same energy at the input, but the fluctuation sits at higher frequency, where the filter attenuates it more.
:::
:::

::: practice

::: check
given: f = 20 | 72; N = 8 | 12
answer: f*1e3/2^N
unit: kHz
tolerance: 0.5%

## What PWM frequency does a {N}-bit counter on a {f} MHz clock give?

::: misses
- [f*1e3/N] There are $2^N$ counts per period.
- [any] $f_{clk}/2^N$.
:::
:::

::: check
given: V = 3.3 | 5; N = 8 | 10 | 12
answer: V/2^N*1e3
unit: mV
tolerance: 0.5%

## What's the step size of an {N}-bit PWM output on {V} V, after filtering?

::: misses
- [V/N*1e3] There are $2^N$ levels.
- [any] $V/2^N$.
:::
:::
:::
