如何使用 Arduino / PlatformIO 使用 ESP32 DAC 正弦/余弦波形发生器

ESP32 及其衍生产品如 ESP32-S2 有一个内置正弦/余弦波形发生器用于内置 8 位 DAC。

使用它需要 ESP-IDF v5.1+(参见官方示例)。在 Arduino 中使用它稍微困难一些,因为撰写本文时 arduino-esp32 框架的稳定版本基于 ESP-IDF v4.4,不提供 DAC 余弦发生器 API。

因此,我们必须在 platformio.ini 中显式指定 arduino-espressif32 版本(git commit):

platformio.ini
[env:esp32dev]
platform = espressif32
# Commit f9cddfde697b659b9e818ec514f1505d2bd4a8ae 是分支 esp-idf-v5.1-libs @2022-02-01
platform_packages = framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git#f9cddfde697b659b9e818ec514f1505d2bd4a8ae
board = esp32dev
framework = arduino

示例主源代码非常简单:

main.cpp
#include <Arduino.h>
#include <driver/dac_cosine.h>

void setup() {
    dac_cosine_handle_t chan0_handle;
    dac_cosine_config_t cos0_cfg = {
        .chan_id = DAC_CHAN_1, // GPIO26
        .freq_hz = 1000,
        .clk_src = DAC_COSINE_CLK_SRC_DEFAULT,
        .atten = DAC_COSINE_ATTEN_DEFAULT,
        .phase = DAC_COSINE_PHASE_0,
        .offset = 0,
        //.flags.force_set_freq = false,
    };
    ESP_ERROR_CHECK(dac_cosine_new_channel(&cos0_cfg, &chan0_handle));
    ESP_ERROR_CHECK(dac_cosine_start(chan0_handle));
}

void loop() {
  // 把你的主要代码放在这里,重复运行:
  delay(1000);
}

如果你想查看生成的波形在示波器上的样子,请查看ESP32 DAC 余弦发生器波形在示波器上看起来如何?


Check out similar posts by category: Arduino, ESP8266/ESP32, PlatformIO