ESP32 best way to generate changeable frequency output on GPIO to drive external device

219 views Asked by At

I'm working on an ESP32 project, several GPIO pins are controlling external devices. I am adding another device that requires a variable clock from 383Khz to 1476Khz approx. To vary the frequency I have a GPIO pin configured as an ADC and connected to a potentiometer. This will update a variable X and this variable will update the frequency output to another GPIO pin to drive the new device.

The question is what is the best way to do this and minimise resources and program memory? Should I use the timer or PCM module or just switched the GPIO pin on and off with nanosec delay? Is it possible to update the devisor for the timer while the program is running? Can the PCM frequency be changed while the program is running? 383Khz to 1476Khz Thanks in advance. And please point me to any code examples and similar resources.

Have not anything yet. Just looking for the best approach.

1

There are 1 answers

0
Matias B On

You can use the LED Control peripheral. It is primarily designed to control the intensity of LEDs, but you can use it to generate a PWM signal of your desired frequency with a 50% duty cycle, which would behave like a clock signal.

This is an example generating a 2.048MHz clock signal:

#include <driver/ledc.h>

ledc_timer_config_t ledc_timer = {
    .speed_mode = LEDC_HIGH_SPEED_MODE,
    .bit_num    = LEDC_TIMER_2_BIT,
    .timer_num  = LEDC_TIMER_0,
    .freq_hz    = 2048000
};
ledc_channel_config_t ledc_channel = {
    .gpio_num   = GPIO_NUM_33,
    .speed_mode = LEDC_HIGH_SPEED_MODE,
    .channel    = LEDC_CHANNEL_0,
    .timer_sel  = LEDC_TIMER_0,
    .duty       = 2
};

ledc_timer_config(&ledc_timer);
ledc_channel_config(&ledc_channel);

You can then use the ledc_set_freq function to change the frequency on the fly.