Try Embedded

Sine wave generator (MCP4725)

A 12-bit DAC turns a table of numbers into a real analog sine wave; watch it on the oscilloscope, and compare it with PWM.

Output · Intermediate

In a real product: Function generator (Industrial): A DAC turns numbers into real analog waveforms.

analogWrite() is not analog: it switches the pin on and off fast and lets you average it. A DAC makes a real voltage. The MCP4725 takes a 12-bit number over I²C and holds VOUT at that fraction of its supply, so stepping through a table of sine values draws a sine wave.

What you'll learn

  • What a DAC is, and how its resolution (4096 steps, 1.2 mV each on 5 V) sets the smallest change it can make
  • Building a lookup table once in setup() instead of calling sin() in the loop
  • What limits the frequency: each sample is an I²C write

How it works

The table holds 64 samples of one cycle, 2048 + 2047 × sin(2π i / 64), from 1 to 4095. The loop writes them one after another with dac.setVoltage(value, false) (false: do not store it in the EEPROM, which wears out). At 400 kHz each write takes about 75 µs, so a cycle of 64 samples is about 5 ms: roughly 200 Hz. The oscilloscope on VOUT shows the steps.

Try this

  • Halve the table to 32 samples: the frequency doubles and the steps get coarser.
  • Write a triangle wave or a sawtooth instead.
  • Move the scope probe to pin 9 and add analogWrite(9, 128): that is PWM, a square wave, not a voltage.

sketch.ino

// A sine wave out of an MCP4725 DAC at 0x62: 64 samples a cycle from a table made in setup(), written as fast as
// I2C allows (about 200 Hz). Watch VOUT on the oscilloscope.
#include <Wire.h>
#include <Adafruit_MCP4725.h>

Adafruit_MCP4725 dac;
const int SAMPLES = 64;
uint16_t sine[SAMPLES];

void setup() {
  Serial.begin(9600);
  if (!dac.begin(0x62)) {
    Serial.println("No MCP4725 at 0x62");
    while (true) {}
  }
  for (int i = 0; i < SAMPLES; i++) sine[i] = 2048 + 2047 * sin(2 * PI * i / SAMPLES);
  Serial.println("Generating a sine wave on VOUT");
}

void loop() {
  for (int i = 0; i < SAMPLES; i++) dac.setVoltage(sine[i], false);
}

Lessons behind it