---
title: The DAC and waveform generation
heading: Making any voltage, and any waveform, from numbers
eyebrow: C12 · Lesson 24 · The DAC and waveform generation
xp: 40
---

::: hook
PWM fakes an analog level by switching fast; a **digital-to-analog converter** produces the level itself. Write a 12-bit number to the DAC and its output pin moves to that fraction of 3.3 V. Write a new number at regular intervals from a table, and the output traces a waveform: a sine for a test signal, a ramp for a sweep, a recorded sound. This is how function generators, audio players and signal synthesizers work inside, and the arithmetic of sample rates and table lengths is C9's sampling theory put to work.
:::

::: play
- A timer interrupts 8000 times a second; each time, the handler writes the next entry of a 32-entry sine table to the DAC. The output is a 250 Hz sine, drawn in steps on the timeline's dac lane.
- Zoom in to see the steps: each lasts one sample period, 125 µs. A low-pass filter after the DAC would smooth them into a clean sine.
- Change TOP from 1249 to 624: the sample rate doubles, and so does the frequency.
:::
:::

```sim board
lang: c
scope: dac | 0..12 ms
run: 20 ms
code:
#include "board.h"

// One period of a sine in 32 samples, from 0 to 4095 around mid-scale
const uint16_t sine[32] = {2048, 2447, 2831, 3185, 3495, 3750, 3939, 4056,
                           4095, 4056, 3939, 3750, 3495, 3185, 2831, 2447,
                           2048, 1648, 1264, 910, 600, 345, 156, 39,
                           0, 39, 156, 345, 600, 910, 1264, 1648};
volatile uint32_t k = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    DAC_DATA = sine[k];
    k = (k + 1) & 31;           // wrap after 32 samples
}

int main(void) {
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 0;
    TIMER_TOP = 1249;           // 10 MHz / 1250 = 8 kHz sample rate
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    while (1)
        __wfi();
}
```

::: predict
## A 64-entry table is played at 16 kHz. What frequency comes out?

- [ ] 64 Hz
- [x] 250 Hz
- [ ] 16 kHz
- [ ] 1 MHz

::: reveal
250 Hz: one full table is one period, and 64 samples at 16,000 per second take 4 ms. Doubling the table's length and the sample rate together keeps the frequency and makes each step smaller.
:::
:::

::: nameit
## The DAC

This board's DAC is 12 bits over 0 to 3.3 V:

$$V = \frac{\text{code}}{4095} \times 3.3$$

so a step is 0.81 mV. In C, `DAC_DATA = code;`; in MicroPython, `DAC(0).write(code)`.

## Table-driven waveforms

A table of N samples, written one every $1/f_s$, repeats at

$$f = \frac{f_s}{N}$$

A sine table centered on mid-scale holds $\text{round}(2047.5 + A\sin(2\pi k/N))$ for an amplitude of A codes. By sampling theory (C9), the output contains the wanted frequency plus images around multiples of $f_s$; a low-pass **reconstruction filter** after the DAC removes them, and the steps with them.

## Any frequency: the phase accumulator

To play frequencies that aren't $f_s/N$ exactly, keep a 32-bit **phase** that grows by a step each sample and wraps around:

```c
phase += step;               // wraps at 2^32: one full period
DAC_DATA = sine[phase >> 27]; // the top 5 bits pick one of 32 entries
```

$$f = f_s\,\frac{\text{step}}{2^{32}}, \qquad \text{step} = \frac{f}{f_s}\,2^{32}$$

This is **direct digital synthesis** (DDS), the heart of most modern signal generators; its frequency resolution is $f_s/2^{32}$.
:::

::: example
## What DAC code gives 1.0 V?

::: solution
1. **Scale the voltage to a code.**
   $$\frac{1.0}{3.3} \times 4095 = 1240.9$$
   so 1241.
2. **Check what it gives.**
   $$1241 \times \frac{3.3}{4095} = 1.0001\ \text{V}$$

**Answer:** code 1241, which gives 1.0001 V.
:::
:::

::: example
## A phase accumulator runs at 10 kHz. What step plays 440 Hz?

::: solution
1. **Step.** Rounded to a whole number:
   $$\frac{440}{10\,000} \times 2^{32} = 188\,978\,561$$
2. **Resolution.**
   $$\frac{10\,000}{2^{32}} = 2.3\ \mu\text{Hz}$$
   so any audible frequency can be set essentially exactly.

**Answer:** a step of 188,978,561.
:::
:::

::: example
## A 32-bit phase accumulator updates at 10 kHz. What is the smallest frequency step it can make?

::: solution
1. **One step of the phase increment.**
   $$\begin{aligned} \Delta f &= \frac{f_s}{2^{32}} \\ &= \frac{10^4}{4.29 \times 10^9}\ \text{Hz} \\ &= 2.33\ \mu\text{Hz} \end{aligned}$$
2. **Where the fine tuning comes from.** Direct digital synthesis gets its extraordinarily fine tuning from the accumulator's width: at the same sample rate, each extra bit halves the step.

**Answer:** 2.33 µHz.
:::
:::

::: check
given: V = 0.5 | 1.25 | 2 | 3
answer: round(V/3.3*4095)
tolerance: 0

## What DAC code gives {V} V?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. $V/3.3 \times 4095$, rounded.
:::
:::

::: check
given: c = 100 | 1000 | 2048 | 4000
answer: c/4095*3.3
unit: V
tolerance: 0.2%

## The DAC holds {c}. What's its output?

::: right
Right. {answer} V.
:::

::: misses
- [any] Not yet. code/4095 × 3.3 V.
:::
:::

::: check
given: fs = 8000 | 16000 | 48000; N = 16 | 32 | 64
answer: fs/N
unit: Hz
tolerance: 0.5%

## A {N}-sample table is played at {fs} samples per second. What frequency comes out?

::: right
Right. $f_s/N$ = {answer} Hz.
:::

::: misses
- [fs*N] One table is one period: divide.
- [any] Not yet. $f_s/N$.
:::
:::

::: check
given: f = 100 | 440 | 1000; N = 32 | 64
answer: f*N/1000
unit: kHz
tolerance: 0.5%

## What sample rate plays a {N}-sample table at {f} Hz?

::: right
Right. $fN$ = {answer} kHz.
:::

::: misses
- [any] Not yet. Samples per period times periods per second.
:::
:::

::: check
given: f = 50 | 440 | 1234; fs = 8000 | 10000
answer: round(f/fs*2^32)
tolerance: 1e-6%

## A phase accumulator updates {fs} times a second. What 32-bit step makes {f} Hz?

::: right
Right. $f/f_s \times 2^{32}$ = {answer}.
:::

::: misses
- [round(fs/f*2^32)] Upside down: the step is the fraction of a period per sample.
- [any] Not yet. $(f/f_s) 2^{32}$.
:::
:::

::: check
given: k = 2 | 5 | 11; N = 32
answer: round(2047.5 + 2047.5*sin(2*pi*k/N))
tolerance: 0

## A full-scale {N}-entry sine table centered at mid-scale: what's entry {k}?

::: right
Right. $\text{round}(2047.5 + 2047.5\sin(2\pi k/N))$ = {answer}.
:::

::: misses
- [any] Not yet. Mid-scale plus the amplitude times the sine.
:::
:::

::: check
kind: choice

## A DAC plays a sine table at 8 kHz. Which component smooths the steps out of the output?

- [ ] A pull-up resistor
- [x] A low-pass filter with its corner below 4 kHz
- [ ] A high-pass filter
- [ ] A faster processor

::: misses
- [1] That only fixes a level; it doesn't smooth.
- [3] That would keep the steps and lose the sine.
- [4] The steps come from the sample rate, not the processor.
:::
:::

::: check
kind: c
given: MV = 500 | 1250 | 2750
run: 0.01
expect: dac = MV/1000 V ± 0.001

## Make the DAC output `MV` millivolts ({MV} mV), as close as its 12 bits allow, using integer arithmetic.

```c starter
#include "board.h"

int main(void) {
    DAC_DATA = MV;
    return 0;
}
```

```c solution
#include "board.h"

int main(void) {
    DAC_DATA = (MV * 4095 + 1650) / 3300;
    return 0;
}
```

::: right
Right. Scale by 4095/3300 with rounding: the output is within half a step, 0.4 mV.
:::
:::

::: check
kind: micropython
given: V = 0.8 | 1.65 | 2.4
run: 0.01
expect: dac = V V ± 0.001

## In MicroPython, set the DAC to {V} V.

```micropython starter
from machine import DAC

dac = DAC(0)
```

```micropython solution
from machine import DAC

dac = DAC(0)
dac.write(round(V / 3.3 * 4095))
```

::: right
Right. The code is the voltage's fraction of 3.3 V, times 4095.
:::
:::

::: check
kind: parts
given: V = 0.25 | 1.2 | 3

## The 12-bit DAC spans 0 to 3.3 V.

::: part
answer: round(V/3.3*4095)
tolerance: 0

### What code gives {V} V?

::: misses
- [any] $V \times 4095/3.3$.
:::
:::

::: part
answer: 3.3/4095*1000
unit: mV
tolerance: 0.5%

### What is one step?

::: misses
- [any] 3.3 V/4095.
:::
:::
:::

::: check
kind: parts
given: fs = 8 | 10 | 48; f = 100 | 440 | 1000; b = 16 | 32

## A {b}-bit phase accumulator updates at {fs} kHz.

::: part
answer: round(f/(fs*1000)*2^b)
tolerance: 0

### What step plays {f} Hz?

::: misses
- [any] $f \cdot 2^b/f_s$, rounded.
:::
:::

::: part
answer: fs*1000/2^b*1000
unit: mHz
tolerance: 0.5%

### What is its frequency resolution?

::: misses
- [any] $f_s/2^b$.
:::
:::
:::

::: explain
## Why does a phase accumulator give finer frequency control than stepping through a table one entry per sample?

::: model
Stepping one entry per sample can only make frequencies $f_s/N$, and other table lengths or sample rates, so most frequencies are out of reach. A phase accumulator advances a 32-bit number by any amount each sample and uses its top bits to choose the table entry, so the table is effectively read at a fractional rate: sometimes the same entry twice, sometimes skipping one. The frequency is $f_s$ times the step over $2^{32}$, and since the step can be any integer, frequencies come in steps of $f_s/2^{32}$, microhertz at audio sample rates. The waveform's shape still comes from the table, so a small table serves every frequency.
:::
:::

::: practice

::: check
given: V = 0.3 | 0.5 | 1 | 1.5 | 2 | 2.8 | 3
answer: round(V/3.3*4095)
tolerance: 0

## DAC code for {V} V?

::: misses
- [any] $V/3.3 \times 4095$.
:::
:::

::: check
given: fs = 20000 | 44100; N = 128 | 256
answer: fs/N
unit: Hz
tolerance: 0.5%

## Frequency of a {N}-sample table at {fs} Hz?

::: misses
- [any] $f_s/N$.
:::
:::

::: check
given: f = 100 | 440 | 1000 | 2000 | 3000 | 5000 | 10000; fs = 48000
answer: round(f/fs*2^32)
tolerance: 1e-6%

## 32-bit DDS step for {f} Hz at {fs} Hz?

::: misses
- [any] $(f/f_s) 2^{32}$.
:::
:::
:::
