Skip to menu

Robotics with Object Pascal

Rover

I asked Google's Gemini, "How to control 2 DC motors with ESP32's two DAC, not with PWM?"

 

AI Overview
To code a Digital-to-Analog Converter (DAC) on an ESP32C3 using the Arduino IDE, you'll primarily use the dacWrite() function, specifying the DAC channel and the desired output value (0-255). The ESP32C3 has two DAC channels, GPIO25 and GPIO26, which can be used as analog outputs. 
This video explains how to use the DAC pins on the ESP32: 
Here's a basic example:
Code
#define DAC_CH1 25 // Define DAC channel 1 (GPIO25)
#define DAC_CH2 26 // Define DAC channel 2 (GPIO26)

void setup() {
  // No setup needed for DAC in this simple example
}

void loop() {
  // Output a value on DAC channel 1
  dacWrite(DAC_CH1, 127); // Output approximately 1.65V (half of 3.3V)
  delay(1000);

  // Output a different value on DAC channel 1
  dacWrite(DAC_CH1, 255); // Output approximately 3.3V
  delay(1000);

  // Output a value on DAC channel 2
  dacWrite(DAC_CH2, 64); // Output approximately 0.825V (quarter of 3.3V)
  delay(1000);

  // Output a different value on DAC channel 2
  dacWrite(DAC_CH2, 0); // Output 0V
  delay(1000);
}
You can watch this video to see an example of using DAC on ESP32:
Explanation:
  1. 1. Define DAC pins:
    Use #define to assign meaningful names (like DAC_CH1DAC_CH2) to the GPIO pins you'll be using for the DAC channels (25 and 26). 
  2. 2. setup() function:
    In this simple example, no specific setup is required for the DAC itself. If you were using the DAC with a more complex system (like I2S for audio), you might need to initialize it in setup(). 
  3. 3. loop() function:
    • dacWrite(DAC_CH1, 127); writes the value 127 (an 8-bit value) to DAC channel 1, corresponding to a voltage of approximately 1.65V (half of the ESP32's 3.3V supply). 
    • dacWrite(DAC_CH1, 255); writes the value 255 to DAC channel 1, resulting in a voltage of approximately 3.3V. 
    • dacWrite(DAC_CH2, 64); writes the value 64 to DAC channel 2, resulting in a voltage of approximately 0.825V. 
    • dacWrite(DAC_CH2, 0); writes the value 0 to DAC channel 2, resulting in a voltage of 0V. 
  4. 4. delay() function:
    The delay() function is used to pause the execution of the loop, allowing you to observe the voltage changes on the DAC pins. 
Key points:
  • The ESP32C3's DAC is an 8-bit DAC, meaning it can output 256 different voltage levels (0-255). 
  • The output voltage is proportional to the value written to the DAC. The relationship is roughly output_voltage = (value / 255.0) * 3.3. 
  • You can use the dacWrite() function with either DAC channel (GPIO25 or GPIO26). 
  • For more complex applications, you might need to consider using the I2S peripheral for higher-quality audio output with the DAC.