Language: EN

esp32-dac

How to use the DAC analog output in an ESP32

The digital-to-analog converter (DAC) is a component that converts a digital signal into a discrete analog signal.

The DAC takes digital numerical values and transforms them into voltage levels. This is particularly useful when it is necessary to control reference voltages, generate custom waveforms, or even work with audio.

Unlike a pseudo-analog signal, such as the one we would obtain with PWM, the DAC generates a “real” analog signal (discrete, stepped, but “truly” analog).

The ESP32 and ESP32-S2 include two integrated DACs, allowing for the generation of analog signals on two independent channels. These channels are known as DAC1 and DAC2, and they can generate voltages in the range of 0 to 3.3 volts.

However, the ESP32-C3 and ESP32-S3 (and this is a real shame) do not include a DAC.

Using the DAC on the ESP32

Using the DAC of the ESP32 in the Arduino environment is very simple. We just need to use the dacWrite function.

Let’s take a basic example of how to generate an analog signal using DAC1:

const int raw = 1500 * 255 / 3300;

void setup() {
  // DAC initialization
  dacWrite(DAC1, raw); // Generates a voltage of approximately 1.5V on DAC1
}

void loop() {
  // No need to do anything in the main loop
}

In this example, the dacWrite() function is used to set the voltage value on the DAC1 channel.

The value passed as an argument is a number between 0 and 255, which corresponds to the voltage in the range of 0 to 3.3V. In this case, it generates a voltage of approximately 1.5V.

Generating more complex signals

While generating a constant voltage is useful, the DAC on the ESP32 can also be used to generate more complex waveforms. For example, we can generate a sine wave using a table of precalculated values:

const int tableSize = 100;
const uint8_t sinTable[tableSize] = {127, 139, 150, ...}; // Precalculated values

int index = 0;

void setup() {
  // DAC configuration
}

void loop() {
  // Signal generation
  dacWrite(DAC1, sinTable[index]);
  index = (index + 1) % tableSize;
  delay(10); // Controls the frequency of the wave
}

In this example, a precalculated table of values is used to generate a sine wave on DAC1. The index is incremented to traverse the table and generate the waveform.