ESP32在休眠模式下保持PWM输出

前言

IDF手册上说如果PWM的clk_cfg配置为RTC8M_CLK支持Light-Sleep模式,但是官方的Repo里面也没有如何使用这个特性的例子.

实操

经过一圈摸索.需要配置menuconfig才行

1
idf.py menuconfig

找到Component config->Hardware Settings -> Sleep Config, 关闭light sleep GPIO reset workaround

在esp-idf内置的LEDC (LED Controller) basic example的基础上修改,得到以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#include <stdio.h>

#include "driver/ledc.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_sleep.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rtc.h"

#define PIN_LED GPIO_NUM_5

static void example_ledc_init(void) {
// Prepare and then apply the LEDC PWM timer configuration
ledc_timer_config_t ledc_timer = {
.duty_resolution = LEDC_TIMER_13_BIT,
.freq_hz = 1000,
.speed_mode = LEDC_LOW_SPEED_MODE,
.timer_num = LEDC_TIMER_0,
.clk_cfg = LEDC_USE_RTC8M_CLK,
};
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

// Prepare and then apply the LEDC PWM channel configuration
ledc_channel_config_t ledc_channel = {.channel = LEDC_CHANNEL_0,
.duty = 128,
.gpio_num = PIN_LED,
.speed_mode = LEDC_LOW_SPEED_MODE,
.hpoint = 0,
.timer_sel = LEDC_TIMER_0};
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
}
void app_main(void) {
// Set the LEDC peripheral configuration
example_ledc_init();
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC8M, ESP_PD_OPTION_ON);
while (1) {
for (int i = 1; i < (1 << 13); i += 128) {
ESP_LOGE("Duty", "Current Duty is %d", i);
ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, i));
// Update duty to apply the new value
ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0));
esp_sleep_enable_timer_wakeup(1000 * 1000 * 1);
esp_light_sleep_start();
}
}
}