</>EmbeddedInterview

How does a DAC work, and how do you generate a waveform with it?

MediumMicrocontrollers & ARM Cortex-M

Short answer: A DAC (digital-to-analogue converter) turns a digital code into a voltage: Vout = code / (2^N) × Vref (for an N-bit DAC). MCU DACs are typically 8–12 bits with a few hundred kHz to a few MHz update rate. To generate a waveform, store one period of samples in a table and have a timer trigger the DAC update while DMA feeds samples from the table in circular mode, so the output frequency is exact and the CPU is not involved.

#include <math.h>
#include <stdint.h>

#define N_SAMPLES 64
static uint16_t sine_table[N_SAMPLES];

void make_sine_table(void)                       /* 12-bit DAC, mid-scale offset */
{
    for (int i = 0; i < N_SAMPLES; i++)
        sine_table[i] = (uint16_t)(2048 + 2047 * sinf(2.0f * 3.14159265f * i / N_SAMPLES));
}
/* Configure: timer update event at f_out * N_SAMPLES (e.g. 1 kHz * 64 = 64 kHz),
   DAC trigger = timer TRGO, DMA circular from sine_table to the DAC data register. */

f_out = f_trigger / N_SAMPLES. More samples per period give a cleaner waveform but require a higher update rate.

Key parameters: resolution, settling time (how long the output takes to reach the new value), output impedance and drive capability (many MCU DACs need the internal output buffer enabled or an external op-amp to drive a load), and reference accuracy.

Cleaning up the output: a DAC produces a staircase; a reconstruction low-pass filter after it removes the step frequency (images around the update rate). The sinc roll-off of a zero-order hold also attenuates higher output frequencies slightly.

DAC types: resistor string, R-2R ladder (common on MCUs), sigma-delta (audio codecs), and PWM + RC filter as a cheap "DAC" when no DAC is available: duty cycle sets the average voltage, at the cost of ripple and slow response.

Uses: audio tones and alerts, generating reference or bias voltages, test signals, setting analogue control inputs (e.g. a laser driver or a motor controller reference), and the internal DAC that sets comparator thresholds.