2

I'm trying to do sort of a frequency sweep using the ESP32's DAC.

Currently I'm not so sure on how to change the frequency without stopping the DAC first. And also stopping the DAC rises an issue since I often get the issue that the DAC has not been stopped before changing and starting again as if stopping the DAC is running in the background but the ESP already continues to the next operation, while stopping the DAC has not finished yet.

What is a good method to change the frequency without stopping the DAC or isn't there any? Is there an alternative method?

#include <math.h>
#include <rom/ets_sys.h>
#include <esp_task_wdt.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/dac_cosine.h"
#include "esp_adc/adc_oneshot.h"
#include "esp_check.h"


dac_cosine_handle_t chan0_handle;

dac_cosine_config_t cos0_cfg = {
    .chan_id = DAC_CHAN_0,                  //  The channel determines the output pin (GPIO 25 OR 17 for channel 0)
    .freq_hz = 1000,                        //  The frequency
    .clk_src = DAC_COSINE_CLK_SRC_DEFAULT,  //  The clock source, only RTC_FAST can be used which is default
    .offset = 0,                            //  DC Offset -128 to 127 (int 8)
    .phase = DAC_COSINE_PHASE_0,            //  Phase of the waveform
    .atten = DAC_COSINE_ATTEN_DEFAULT,      //  attenuation, default = max 3v3pp
    .flags.force_set_freq = false,          
};

void set_frequency(uint32_t frequency) {
    cos0_cfg.freq_hz = frequency;

    ESP_ERROR_CHECK(dac_cosine_stop(chan0_handle));
    ESP_ERROR_CHECK(dac_cosine_del_channel(&chan0_handle));
    ESP_ERROR_CHECK(dac_cosine_new_channel(&cos0_cfg, &chan0_handle));
    ESP_ERROR_CHECK(dac_cosine_start(chan0_handle));
}

void sweep() {
    int freq = 1000;
    while(true) {
        set_frequency(freq);
        freq += 1000;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        if(freq > 10000) {
            freq = 1000;
        }
    }
    
}

void app_main(void)
{
    ESP_ERROR_CHECK(dac_cosine_new_channel(&cos0_cfg, &chan0_handle));
    ESP_ERROR_CHECK(dac_cosine_start(chan0_handle));

    xTaskCreate(sweep, "sweeping", 4096, NULL, 5, NULL);
}
Mart
  • 475
  • 4
  • 21

0 Answers0