I'm using ESP32-S2 with esp-idf v5.0.2 and trying to generate clock signal for external device. So I wrote the following code, basically modified from example code:
Code: Select all
void PWM_Init(){
// Prepare and then apply the LEDC PWM timer configuration
ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.timer_num = LEDC_TIMER_0,
.duty_resolution = LEDC_TIMER_1_BIT,
.freq_hz = 1000,
.clk_cfg = LEDC_AUTO_CLK
};
esp_err_t ret = ledc_timer_config(&ledc_timer);
if(ret != ESP_OK){
printf("err=%d\n", ret);
}
// Prepare and then apply the LEDC PWM channel configuration
ledc_channel_config_t ledc_channel = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0,
.timer_sel = LEDC_TIMER_0,
.intr_type = LEDC_INTR_DISABLE,
.gpio_num = GPIO_PWM,
.duty = 1,
.hpoint = 0
};
ret = ledc_channel_config(&ledc_channel);
if(ret != ESP_OK){
printf("err=%d\n", ret);
}
}
void PWM_Start(uint32_t freq){
esp_err_t ret = ledc_set_freq(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, freq);
if(ret != ESP_OK){
printf("err=%d\n", ret);
}
}
Code: Select all
void app_main(void){
//Blink_Init();
//ST7789_Init();
PWM_Init();
//ST7789_FillColor(0xFFFFFFFF);
//Blink_Start(1000);
PWM_Start(4194304);
while(1){
//for(int i = 0; i < 160 * 144; ++i){
// pixelData[i] = (uint16_t)rand();
//}
//ST7789_Flush((uint8_t*)pixelData, (240 - 160) >> 1, (240 - 144) >> 1, 160, 144);
vTaskDelay(100 / portTICK_PERIOD_MS);
//printf("counter=%ld.\n", counter);
//counter++;
}
}
Code: Select all
E (1555) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=0
I only need freq @ 4MHz with duty @ 50%. Why I got this error?The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other devices, e.g., a digital camera module. In this case, the maximum available frequency is 40 MHz with duty resolution of 1 bit. This means that the duty cycle is fixed at 50% and cannot be adjusted.
The LEDC API is designed to report an error when trying to set a frequency and a duty resolution that exceed the range of LEDC’s hardware. For example, an attempt to set the frequency to 20 MHz and the duty resolution to 3 bits will result in the following error reported on a serial monitor:
E (196) ledc: requested frequency and duty resolution cannot be achieved, try reducing freq_hz or duty_resolution. div_param=128
In such a situation, either the duty resolution or the frequency must be reduced. For example, setting the duty resolution to 2 will resolve this issue and will make it possible to set the duty cycle at 25% steps, i.e., at 25%, 50% or 75%.
Any advice is much apprecicated!