# LED PWM 控制器

[English]

## 概述

LED 控制器 (LEDC) 主要用于控制 LED，也可产生 PWM 信号用于其他设备的控制。该控制器有 8 路通道，可以产生独立的波形，驱动 RGB LED 等设备。

LED PWM 控制器可在无需 CPU 干预的情况下自动改变占空比，实现亮度和颜色渐变。

## 功能概览

设置 LEDC 通道分三步完成。注意，与 ESP32 不同，ESP32-S31 仅支持设置通道为低速模式。

1. 定时器配置 指定 PWM 信号的频率和占空比分辨率。

2. 通道配置 绑定定时器和输出 PWM 信号的 GPIO。

3. 改变 PWM 信号 输出 PWM 信号来驱动 LED。可通过软件控制或使用硬件渐变功能来改变 LED 的亮度。

另一个可选步骤是可以在渐变终端设置一个中断。

LED PWM 控制器 API 的关键配置

备注

首次 LEDC 配置时，建议先配置定时器（调用函数 `ledc_timer_config()`），再配置通道（调用函数 `ledc_channel_config()`）。这样可以确保 IO 脚上的 PWM 信号自有输出开始其频率就是正确的。

### 定时器配置

要设置定时器，可调用函数 `ledc_timer_config()`，并将包括如下配置参数的数据结构 `ledc_timer_config_t` 传递给该函数：

- 速度模式（值必须为 `LEDC_LOW_SPEED_MODE`）

- 定时器索引 `ledc_timer_t`

- PWM 信号频率（Hz）

- PWM 占空比分辨率

- 时钟源 `ledc_clk_cfg_t`

频率和占空比分辨率相互关联。PWM 频率越高，占空比分辨率越低，反之亦然。如果 API 不是用来改变 LED 亮度，而是用于其它目的，这种相互关系可能会很重要。更多信息详见 频率和占空比分辨率支持范围 一节。

时钟源同样可以限制 PWM 频率。选择的时钟源频率越高，可以配置的 PWM 频率上限就越高。

ESP32-S31 LEDC 时钟源特性
时钟名称 | 时钟频率 | 时钟功能
--- | --- | ---
PLL_80M_CLK | 80 MHz | /
RC_FAST_CLK | ~ 17.5 MHz | 支持动态调频 (DFS) 功能，支持 Light-sleep 模式
XTAL_CLK | 40 MHz | 支持动态调频 (DFS) 功能

备注

1. 如果 ESP32-S31 的定时器选用了 `RC_FAST_CLK` 作为其时钟源，驱动会通过内部校准来得知这个时钟源的实际频率。这样确保了输出 PWM 信号频率的精准性。

2. ESP32-S31 的所有定时器共用一个时钟源。因此 ESP32-S31 不支持给不同的定时器配置不同的时钟源。

LEDC 驱动提供了一个辅助函数 `ledc_find_suitable_duty_resolution()`。传入时钟源频率及期望的 PWM 信号频率，这个函数可以直接找到最大可配的占空比分辨率值。

当一个定时器不再被任何通道所需要时，可以通过调用相同的函数 `ledc_timer_config()` 来重置这个定时器。此时，函数入参的配置结构体需要指定：

- `ledc_timer_config_t::speed_mode` 重置定时器的所属速度模式 （`ledc_mode_t`）

- `ledc_timer_config_t::timer_num` 重置定时器的索引 （`ledc_timer_t`）

- `ledc_timer_config_t::deconfigure` 将指定定时器重置必须配置此项为 true

### 通道配置

定时器设置好后，请配置所需的通道（`ledc_channel_t` 之一）。配置通道需调用函数 `ledc_channel_config()`。

通道的配置与定时器设置类似，需向通道配置函数传递包括通道配置参数的结构体 `ledc_channel_config_t` 。

此时，通道会按照 `ledc_channel_config_t` 的配置开始运作，并在选定的 GPIO 上生成由定时器设置指定的频率和占空比的 PWM 信号。在通道运作过程中，可以随时通过调用函数 `ledc_stop()` 将其暂停。

### 改变 PWM 信号

通道开始运行、生成具有恒定占空比和频率的 PWM 信号之后，有几种方式可以改变该信号。驱动 LED 时，主要通过改变占空比来变化光线亮度。

以下两节介绍了如何使用软件和硬件改变占空比。如有需要，PWM 信号的频率也可更改，详见 改变 PWM 频率 一节。

备注

在 ESP32-S31 的 LED PWM 控制器中，所有的定时器和通道都只支持低速模式。对 PWM 设置的任何改变，都需要由软件显式地触发（见下文）。

#### 使用软件改变 PWM 占空比

调用函数 `ledc_set_duty()` 可以设置新的占空比。之后，调用函数 `ledc_update_duty()` 使新配置生效。要查看当前设置的占空比，可使用 `_get_` 函数 `ledc_get_duty()`。

另外一种设置占空比和其他通道参数的方式是调用 通道配置 一节提到的函数 `ledc_channel_config()`。

传递给函数的占空比数值范围取决于选定的 `duty_resolution`，应为 `0` 至 `(2 ** duty_resolution)`。例如，如选定的占空比分辨率为 10，则占空比的数值范围为 0 至 1024。此时分辨率为 ~ 0.1%。

#### 使用硬件改变 PWM 占空比

LED PWM 控制器硬件可逐渐改变占空比的数值。要使用此功能，需用函数 `ledc_fade_func_install()` 使能渐变，之后用下列可用渐变函数之一配置：

- `ledc_set_fade_with_time()`

- `ledc_set_fade_with_step()`

- `ledc_set_fade()`

ESP32-S31 的硬件额外支持无需 CPU 介入的连续渐变。此功能可以更加有效便捷得实现一个带伽马校正的渐变。

众所周知，人眼所感知的亮度与 PWM 占空比并非成线性关系。为了能使人感观上认为一盏灯明暗的变化是线性的，我们对其 PWM 信号的占空比控制必须为非线性的，俗称伽马校正。LED PWM 控制器可以通过多段线型拟合来模仿伽马曲线渐变。 你需要自己在应用程序中分配一段用以保存渐变参数的内存块，并提供开始和结束的占空比，伽马校正公式，以及期望的线性渐变段数信息，`ledc_fill_multi_fade_param_list()` 就能快速生成所有分段线性渐变的参数。或者你也可以自己直接构造一个 `ledc_fade_param_config_t` 的数组。在获得所有渐变参数后，通过将 `ledc_fade_param_config_t` 数组的指针和渐变区间数传入 `ledc_set_multi_fade()`，一次连续渐变的配置就完成了。

最后需要调用 `ledc_fade_start()` 开启渐变。渐变可以在阻塞或非阻塞模式下运行，具体区别请查看 `ledc_fade_mode_t`。需要特别注意的是，不管在哪种模式下，下一次渐变或是单次占空比配置的指令生效都必须等到前一次渐变完成或被中止。中止一个正在运行中的渐变需要调用函数 `ledc_fade_stop()`。

此外，在使能渐变后，每个通道都可以额外通过调用 `ledc_cb_register()` 注册一个回调函数用以获得渐变完成的事件通知。回调函数的原型被定义在 `ledc_cb_t`。每个回调函数都应当返回一个布尔值给驱动的中断处理函数，用以表示是否有高优先级任务被其唤醒。此外，值得注意的是，由于驱动的中断处理函数被放在了 IRAM 中， 回调函数和其调用的函数也需要被放在 IRAM 中。 `ledc_cb_register()` 会检查回调函数及函数上下文的指针地址是否在正确的存储区域。

如不需要渐变和渐变中断，可用函数 `ledc_fade_func_uninstall()` 关闭。

#### 改变 PWM 频率

LED PWM 控制器 API 有多种方式即时改变 PWM 频率：

> - 通过调用函数 `ledc_set_freq()` 设置频率。可用函数 `ledc_get_freq()` 查看当前频率。

> - 通过调用函数 `ledc_bind_channel_timer()` 将其他定时器绑定到该通道来改变频率和占空比分辨率。

> - 通过调用函数 `ledc_channel_config()` 改变通道的定时器。

#### 控制 PWM 的更多方式

有一些较独立的定时器特定函数可用于更改 PWM 输出：

- `ledc_timer_rst()`

- `ledc_timer_pause()`

- `ledc_timer_resume()`

第一个定时器复位函数在函数 `ledc_timer_config()` 内部完成所有定时器配置后会被调用一次。

## LEDC 的 ETM 事件和任务

LEDC 可以生成多种事件，这些事件可以连接到 ETM 模块。定时器支持的事件列在 `ledc_timer_etm_event_type_t` 中，通道支持的事件列在 `ledc_channel_etm_event_type_t` 中。用户可以分别通过调用 `ledc_timer_new_etm_event()` 或 `ledc_channel_new_etm_event()` 来创建 `ETM event` 句柄。 LEDC 还支持一些可由其他事件触发并自动执行的任务。定时器支持的任务列在 `ledc_timer_etm_task_type_t` 中，通道支持的任务列在 `ledc_channel_etm_task_type_t` 中。用户可以分别通过调用 `ledc_timer_new_etm_task()` 或 `ledc_channel_new_etm_task()` 来创建 `ETM task` 句柄。

一些使用 ETM 与 LEDC 结合的实用应用包括：

> - 生成一段特定脉冲数的 PWM 信号

> - 同步 PWM 周期与外部信号

> - 无需 CPU 干预即可开始 / 停止 PWM 信号输出或一次渐变

关于如何将 LEDC 事件和任务连接到 ETM 通道，请参考 ETM 文档。

## 电源管理

LEDC 驱动不使用电源管理锁来防止系统进入 Light-sleep 。相反，可以通过配置 `ledc_channel_config_t::sleep_mode` 来选择 LEDC 外设电源域状态和 PWM 信号在睡眠期间的输出行为。默认模式是 `LEDC_SLEEP_MODE_NO_ALIVE_NO_PD`，它表示没有信号输出，并且 LEDC 电源域在睡眠期间不会下电。

如果需要在 Light-sleep 中保持信号输出，则可以选择 `LEDC_SLEEP_MODE_KEEP_ALIVE` 模式。只要绑定的 LEDC 定时器时钟源兼容 Light-sleep ， PWM 信号就可以在系统进入 Light-sleep 期间继续输出。其代价是睡眠期间的功耗会更高，这是由于时钟源和 LEDC 所属的电源域无法被下电。值得注意的是，在入睡前未完成的渐变也可以在睡眠期间继续，只是有可能没法准确停在目标占空比上。系统被唤醒后，驱动会调整 PWM 占空比到原来设定的目标占空比上。

此外还有另一种睡眠模式，`LEDC_SLEEP_MODE_NO_ALIVE_ALLOW_PD` 。选择此模式可以在睡眠中节省一些功耗，但会消耗更多内存。在进入 Light-sleep 之前，系统会保存 LEDC 寄存器上下文，并在唤醒后恢复它们，从而使 LEDC 电源域可以在睡眠期间被下电。任何未完成的渐变在从睡眠状态唤醒后都不会继续进行，而是输出一个固定占空比的 PWM 信号，该占空比与进入睡眠前的当下占空比相匹配。

## 频率和占空比分辨率支持范围

LED PWM 控制器主要用于驱动 LED。该控制器 PWM 占空比设置的分辨率范围较广。比如，PWM 频率为 5 kHz 时，占空比分辨率最大可为 13 位。这意味着占空比可为 0 至 100% 之间的任意值，分辨率为 ~0.012%（2 ** 13 = 8192 LED 亮度的离散电平）。然而，这些参数取决于为 LED PWM 控制器定时器计时的时钟信号，LED PWM 控制器为通道提供时钟（具体可参考 定时器配置 和 ESP32-S31 技术参考手册 > LED PWM 计时器 (LEDC) [PDF]）。

LED PWM 控制器可用于生成频率较高的信号，足以为数码相机模组等其他设备提供时钟。此时，最大频率可为 40 MHz，占空比分辨率为 1 位。也就是说，占空比固定为 50%，无法调整。

LED PWM 控制器 API 会在设定的频率和占空比分辨率超过 LED PWM 控制器硬件范围时报错。例如，试图将频率设置为 20 MHz、占空比分辨率设置为 3 位时，串行端口监视器上会报告如下错误：

    E (196) ledc: requested frequency and duty resolution cannot be achieved, try reducing freq_hz or duty_resolution. div_param=128

此时，占空比分辨率或频率必须降低。比如，将占空比分辨率设置为 2 会解决这一问题，让占空比设置为 25% 的倍数，即 25%、50% 或 75%。

如设置的频率和占空比分辨率低于所支持的最低值，LED PWM 驱动器也会反映并报告，如：

    E (196) ledc: requested frequency and duty resolution cannot be achieved, try increasing freq_hz or duty_resolution. div_param=128000000

占空比分辨率通常用 `ledc_timer_bit_t` 设置，范围是 10 至 15 位。如需较低的占空比分辨率（上至 10，下至 1），可直接输入相应数值。

## 应用示例

- peripherals/ledc/ledc_basic 演示了如何使用 LEDC 生成低速模式的 PWM 信号。

- peripherals/ledc/ledc_fade 演示了如何使用 LEDC 实现 LED 亮度的渐变控制。

- peripherals/ledc/ledc_gamma_curve_fade 演示了如何使用 LEDC 对 RGB LED 实现带伽马校正的颜色控制。

- peripherals/ledc/ledc_dimmer 演示了如何使用 LEDC 和 ETM 生成与交流电零交叉同步的 TRIAC 门触发脉冲。

## API 参考

### Header File

- components/esp_driver_ledc/include/driver/ledc.h

- This header file can be included with:

  >     #include "driver/ledc.h"

- This header file is a part of the API provided by the `esp_driver_ledc` component. To declare that your component depends on `esp_driver_ledc`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_driver_ledc

  > or

  >     PRIV_REQUIRES esp_driver_ledc

### Functions

esp_err_t ledc_channel_config(const ledc_channel_config_t *ledc_conf)

  LEDC channel configuration Configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC duty.

  参数:

    ledc_conf -- Pointer of LEDC channel configure struct

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

uint32_t ledc_find_suitable_duty_resolution(uint32_t src_clk_freq, uint32_t timer_freq)

  Helper function to find the maximum possible duty resolution in bits for ledc_timer_config()

  参数:

    - src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of `ledc_clk_cfg_t` or get from `esp_clk_tree_src_get_freq_hz`)

    - timer_freq -- Desired LEDC timer frequency (Hz)

  返回:

    - 0 The timer frequency cannot be achieved

    - Others The largest duty resolution value to be set

esp_err_t ledc_timer_config(const ledc_timer_config_t *timer_conf)

  LEDC timer configuration Configure LEDC timer with the given source timer/frequency(Hz)/duty_resolution.

  参数:

    timer_conf -- Pointer of LEDC timer configure struct

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution.

    - ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused

esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel)

  LEDC update channel parameters.

  备注

  Call this function to activate the LEDC updated parameters. After ledc_set_duty, we need to call this function to update the settings. And the new LEDC parameters don't take effect until the next PWM cycle.

  备注

  ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update

  备注

  If `CONFIG_LEDC_CTRL_FUNC_IN_IRAM` is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled.

  备注

  This function is allowed to run within ISR context.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t ledc_set_pin(int gpio_num, ledc_mode_t speed_mode, ledc_channel_t channel)

  Set LEDC output gpio.

  备注

  This function only routes the LEDC signal to GPIO through matrix, other LEDC resources initialization are not involved. Please use `ledc_channel_config()` instead to fully configure a LEDC channel.

  参数:

    - gpio_num -- The LEDC output gpio

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t ledc_stop(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t idle_level)

  LEDC stop. Disable LEDC output, and set idle level.

  备注

  If `CONFIG_LEDC_CTRL_FUNC_IN_IRAM` is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled.

  备注

  This function is allowed to run within ISR context.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - idle_level -- Set output idle level after LEDC stops.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t freq_hz)

  LEDC set channel frequency (Hz)

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - timer_num -- LEDC timer index (0-3), select from ledc_timer_t

    - freq_hz -- Set the LEDC frequency

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution.

uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num)

  LEDC get channel frequency (Hz)

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - timer_num -- LEDC timer index (0-3), select from ledc_timer_t

  返回:

    - 0 error

    - Others Current LEDC frequency

esp_err_t ledc_set_duty_with_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint)

  LEDC set duty and hpoint value Only after calling ledc_update_duty will the duty update.

  备注

  ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)]

    - hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1]

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

int ledc_get_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel)

  LEDC get hpoint value, the counter value when the output is set high level.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

  返回:

    - LEDC_ERR_VAL if parameter error

    - Others Current hpoint value of LEDC channel

esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty)

  LEDC set duty This function do not change the hpoint value of this channel. if needed, please call ledc_set_duty_with_hpoint. only after calling ledc_update_duty will the duty update.

  备注

  ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)]

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

uint32_t ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel)

  LEDC get duty This function returns the duty at the present PWM cycle. You shouldn't expect the function to return the new duty in the same cycle of calling ledc_update_duty, because duty update doesn't take effect until the next cycle.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

  返回:

    - LEDC_ERR_DUTY if parameter error

    - Others Current LEDC duty

esp_err_t ledc_set_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, ledc_duty_direction_t fade_direction, uint32_t step_num, uint32_t duty_cycle_num, uint32_t duty_scale)

  LEDC set gradient Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)]

    - fade_direction -- Set the direction of the gradient

    - step_num -- Set the number of the gradient

    - duty_cycle_num -- Set how many LEDC tick each time the gradient lasts

    - duty_scale -- Set gradient change amplitude

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t ledc_isr_register(void (*fn)(void*), void *arg, int intr_alloc_flags, ledc_isr_handle_t *handle)

  Register LEDC interrupt handler, the handler is an ISR. The handler will be attached to the same CPU core that this function is running on.

  参数:

    - fn -- Interrupt handler function.

    - arg -- User-supplied argument passed to the handler function.

    - intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.

    - handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_NOT_FOUND Failed to find available interrupt source

esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, ledc_timer_t timer_sel)

  Reset LEDC timer.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - timer_sel -- LEDC timer index (0-3), select from ledc_timer_t

  返回:

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_OK Success

esp_err_t ledc_timer_pause(ledc_mode_t speed_mode, ledc_timer_t timer_sel)

  Pause LEDC timer counter.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - timer_sel -- LEDC timer index (0-3), select from ledc_timer_t

  返回:

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_OK Success

esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, ledc_timer_t timer_sel)

  Resume LEDC timer.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - timer_sel -- LEDC timer index (0-3), select from ledc_timer_t

  返回:

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_OK Success

esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_timer_t timer_sel)

  Bind LEDC channel with the selected timer.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - timer_sel -- LEDC timer index (0-3), select from ledc_timer_t

  返回:

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_OK Success

esp_err_t ledc_channel_configure_maximum_timer_ovf_cnt(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t max_ovf_cnt)

  Configure the maximum timer overflow times for the LEDC channel to be used to trigger `LEDC_ETM_EVENT_CHANNEL_REACH_MAX_OVF_CNT` ETM event.

  When the overflow counter maximum value is re-configured, the counter will also be reset. Timer can be paused before calling this API by calling `ledc_timer_pause()`, and resumed afterwards by calling `ledc_timer_resume()`.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - max_ovf_cnt -- The timer overflow counter maximum value. To disable the timer overflow count, set this parameter to 0.

  返回:

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_OK Success

esp_err_t ledc_set_fade_with_step(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num)

  Set LEDC fade function.

  备注

  Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading.

  备注

  ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - target_duty -- Target duty of fading [0, (2**duty_resolution)]

    - scale -- Controls the increase or decrease step scale.

    - cycle_num -- increase or decrease the duty every cycle_num cycles

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_fade_with_time(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, int desired_fade_time_ms)

  Set LEDC fade function, with a limited time.

  备注

  Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading.

  备注

  ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - target_duty -- Target duty of fading [0, (2**duty_resolution)]

    - desired_fade_time_ms -- The intended time of the fading ( ms ). Note that the actual time it takes to complete the fade could vary by a factor of up to 2x shorter or longer than the expected time due to internal rounding errors in calculations. Specifically:

      - The total number of cycles (total_cycle_num = desired_fade_time_ms * freq / 1000)

      - The difference in duty cycle (duty_delta = |target_duty - current_duty|) The fade may complete faster than expected if total_cycle_num larger than duty_delta. Conversely, it may take longer than expected if total_cycle_num is less than duty_delta. The closer the ratio of total_cycle_num/duty_delta (or its inverse) is to a whole number (the floor value), the more accurately the actual fade duration will match the intended time. If an exact fade time is expected, please consider to split the entire fade into several smaller linear fades. The split should make each fade step has a divisible total_cycle_num/duty_delta (or its inverse) ratio.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_fade_func_install(int intr_alloc_flags)

  Install LEDC fade function. This function will occupy interrupt of LEDC module.

  参数:

    intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Intr flag error

    - ESP_ERR_NOT_FOUND Failed to find available interrupt source

    - ESP_ERR_INVALID_STATE Fade function already installed / LEDC not initialized

void ledc_fade_func_uninstall(void)

  Uninstall LEDC fade function.

esp_err_t ledc_fade_start(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_fade_mode_t fade_mode)

  Start LEDC fading.

  备注

  Call ledc_fade_func_install() once before calling this function. Call this API right after ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading.

  备注

  Starting fade operation with this API is not thread-safe, use with care.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel number

    - fade_mode -- Whether to block until fading done. See ledc_types.h ledc_fade_mode_t for more info. Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed.

    - ESP_ERR_INVALID_ARG Parameter error.

esp_err_t ledc_fade_stop(ledc_mode_t speed_mode, ledc_channel_t channel)

  Stop LEDC fading. The duty of the channel is guaranteed to be fixed at most one PWM cycle after the function returns.

  备注

  This API can be called if a new fixed duty or a new fade want to be set while the last fade operation is still running in progress.

  备注

  Call this API will abort the fading operation only if it was started by calling ledc_fade_start with LEDC_FADE_NO_WAIT mode.

  备注

  If a fade was started with LEDC_FADE_WAIT_DONE mode, calling this API afterwards has no use in stopping the fade. Fade will continue until it reaches the target duty.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel number

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_duty_and_update(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint)

  A thread-safe API to set duty for LEDC channel and return when duty updated.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)]

    - hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1]

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_fade_time_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t desired_fade_time_ms, ledc_fade_mode_t fade_mode)

  A thread-safe API to set and start LEDC fade function, with a limited time.

  备注

  Call ledc_fade_func_install() once, before calling this function.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - target_duty -- Target duty of fading [0, (2**duty_resolution)]

    - desired_fade_time_ms -- The intended time of the fading ( ms ). Note that the actual time it takes to complete the fade could vary by a factor of up to 2x shorter or longer than the expected time due to internal rounding errors in calculations. Specifically:

      - The total number of cycles (total_cycle_num = desired_fade_time_ms * freq / 1000)

      - The difference in duty cycle (duty_delta = |target_duty - current_duty|) The fade may complete faster than expected if total_cycle_num larger than duty_delta. Conversely, it may take longer than expected if total_cycle_num is less than duty_delta. The closer the ratio of total_cycle_num/duty_delta (or its inverse) is to a whole number (the floor value), the more accurately the actual fade duration will match the intended time. If an exact fade time is expected, please consider to split the entire fade into several smaller linear fades. The split should make each fade step has a divisible total_cycle_num/duty_delta (or its inverse) ratio.

    - fade_mode -- choose blocking or non-blocking mode

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_fade_step_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num, ledc_fade_mode_t fade_mode)

  A thread-safe API to set and start LEDC fade function.

  备注

  Call ledc_fade_func_install() once before calling this function.

  备注

  For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - target_duty -- Target duty of fading [0, (2**duty_resolution)]

    - scale -- Controls the increase or decrease step scale.

    - cycle_num -- increase or decrease the duty every cycle_num cycles

    - fade_mode -- choose blocking or non-blocking mode

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_cb_register(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_cbs_t *cbs, void *user_arg)

  LEDC callback registration function.

  备注

  The callback is called from an ISR, it must never attempt to block, and any FreeRTOS API called must be ISR capable.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - cbs -- Group of LEDC callback functions

    - user_arg -- user registered data for the callback function

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_multi_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t start_duty, const ledc_fade_param_config_t *fade_params_list, uint32_t list_len)

  Set a LEDC multi-fade.

  备注

  Call `ledc_fade_func_install()` once before calling this function. Call `ledc_fade_start()` after this to start fading.

  备注

  This function is not thread-safe, do not call it to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_multi_fade_and_start

  备注

  This function does not prohibit from duty overflow. User should take care of this by themselves. If duty overflow happens, the PWM signal will suddenly change from 100% duty cycle to 0%, or the other way around.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - start_duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)]

    - fade_params_list -- Pointer to the array of fade parameters for a multi-fade

    - list_len -- Length of the fade_params_list, i.e. number of fade ranges for a multi-fade (1 - SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX)

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_set_multi_fade_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t start_duty, const ledc_fade_param_config_t *fade_params_list, uint32_t list_len, ledc_fade_mode_t fade_mode)

  A thread-safe API to set and start LEDC multi-fade function.

  备注

  Call `ledc_fade_func_install()` once before calling this function.

  备注

  Fade will always begin from the current duty cycle. Make sure it is stable and synchronized to the desired initial value before calling this function. Otherwise, you may see unexpected duty change.

  备注

  This function does not prohibit from duty overflow. User should take care of this by themselves. If duty overflow happens, the PWM signal will suddenly change from 100% duty cycle to 0%, or the other way around.

  参数:

    - speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - start_duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)]

    - fade_params_list -- Pointer to the array of fade parameters for a multi-fade

    - list_len -- Length of the fade_params_list, i.e. number of fade ranges for a multi-fade (1 - SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX)

    - fade_mode -- Choose blocking or non-blocking mode

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Fade function init error

esp_err_t ledc_fill_multi_fade_param_list(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t start_duty, uint32_t end_duty, uint32_t linear_phase_num, uint32_t max_fade_time_ms, uint32_t (*gamma_correction_operator)(uint32_t), uint32_t fade_params_list_size, ledc_fade_param_config_t *fade_params_list, uint32_t *hw_fade_range_num)

  Helper function to fill the fade params for a multi-fade. Useful if desires a gamma curve fading.

  备注

  The fade params are calculated based on the given start_duty and end_duty. If the duty is not at the start duty (gamma-corrected) when the fade begins, you may see undesired brightness change. Therefore, please always remember thet when passing the fade_params to either `ledc_set_multi_fade` or `ledc_set_multi_fade_and start`, the start_duty argument has to be the gamma-corrected start_duty.

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- [in] LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - start_duty -- [in] Duty cycle [0, (2**duty_resolution)] where the multi-fade begins with. This value should be a non-gamma-corrected duty cycle.

    - end_duty -- [in] Duty cycle [0, (2**duty_resolution)] where the multi-fade ends with. This value should be a non-gamma-corrected duty cycle.

    - linear_phase_num -- [in] Number of linear fades to simulate a gamma curved fade (1 - SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX)

    - max_fade_time_ms -- [in] The maximum time of the fading ( ms ).

    - gamma_correction_operator -- [in] User provided gamma correction function. The function argument should be able to take any value within [0, (2**duty_resolution)]. And returns the gamma-corrected duty cycle.

    - fade_params_list_size -- [in] The size of the fade_params_list user allocated (1 - SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX)

    - fade_params_list -- [out] Pointer to the array of ledc_fade_param_config_t structure

    - hw_fade_range_num -- [out] Number of fade ranges for this multi-fade

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

    - ESP_FAIL Required number of hardware ranges exceeds the size of the ledc_fade_param_config_t array user allocated

esp_err_t ledc_read_fade_param(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t range, uint32_t *dir, uint32_t *cycle, uint32_t *scale, uint32_t *step)

  Get the fade parameters that are stored in gamma ram for a certain fade range.

  Gamma ram is where saves the fade parameters for each fade range. The fade parameters are written in during fade configuration. When fade begins, the duty will change according to the parameters in gamma ram.

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.

    - channel -- [in] LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t

    - range -- [in] Range index (0 - (SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX-1)), it specifies to which range in gamma ram to read

    - dir -- [out] Pointer to accept fade direction value

    - cycle -- [out] Pointer to accept fade cycle value

    - scale -- [out] Pointer to accept fade scale value

    - step -- [out] Pointer to accept fade step value

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Channel not initialized

### Structures

struct ledc_channel_config_t

  Configuration parameters of LEDC channel for ledc_channel_config function.

  Public Members

  int gpio_num

    the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16

  ledc_mode_t speed_mode

    LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode

  ledc_channel_t channel

    LEDC channel (0 - LEDC_CHANNEL_MAX-1)

  ledc_intr_type_t intr_type

    Deprecated:

      , no need to explicitly configure interrupt, handled in the driver

  ledc_timer_t timer_sel

    Select the timer source of channel (0 - LEDC_TIMER_MAX-1)

  uint32_t duty

    LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)]

  int hpoint

    LEDC channel hpoint value, the range is [0, (2**duty_resolution)-1]

  ledc_sleep_mode_t sleep_mode

    choose the desired behavior for the LEDC channel in Light-sleep

  struct ledc_channel_config_t::ledc_channel_flags flags

    Extra configuration flags for LEDC channel

  bool deconfigure

    Set this field to de-configure a LEDC channel which has been configured before The driver only does limited action to release the pins occupied by this channel only. When this field is set, gpio_num, timer_sel, duty, hpoint, sleep_mode, flags fields are ignored.

  struct ledc_channel_flags

    Extra configuration flags for LEDC channel.

    Public Members

    unsigned int output_invert

      Enable (1) or disable (0) gpio output invert

struct ledc_timer_config_t

  Configuration parameters of LEDC timer for ledc_timer_config function.

  Public Members

  ledc_mode_t speed_mode

    LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode

  ledc_timer_bit_t duty_resolution

    LEDC channel duty resolution

  ledc_timer_t timer_num

    The timer source of channel (0 - LEDC_TIMER_MAX-1)

  uint32_t freq_hz

    LEDC timer frequency (Hz)

  ledc_clk_cfg_t clk_cfg

    Configure LEDC source clock from ledc_clk_cfg_t. Note that LEDC_USE_RC_FAST_CLK and LEDC_USE_XTAL_CLK are non-timer-specific clock sources. You can not have one LEDC timer uses RC_FAST_CLK as the clock source and have another LEDC timer uses XTAL_CLK as its clock source. All chips except esp32 and esp32s2 do not have timer-specific clock sources, which means clock source for all timers must be the same one.

  bool deconfigure

    Set this field to de-configure a LEDC timer which has been configured before Note that it will not check whether the timer wants to be de-configured is binded to any channel. Also, the timer has to be paused first before it can be de-configured. When this field is set, duty_resolution, freq_hz, clk_cfg fields are ignored.

struct ledc_cb_param_t

  LEDC callback parameter.

  Public Members

  ledc_cb_event_t event

    Event name

  uint32_t speed_mode

    Speed mode of the LEDC channel group

  uint32_t channel

    LEDC channel (0 - LEDC_CHANNEL_MAX-1)

  uint32_t duty

    LEDC current duty of the channel, the range of duty is [0, (2**duty_resolution)]

struct ledc_cbs_t

  Group of supported LEDC callbacks.

  备注

  The callbacks are all running under ISR environment

  Public Members

  ledc_cb_t fade_cb

    LEDC fade_end callback function

struct ledc_fade_param_config_t

  Structure for the fade parameters for one hardware fade to be written to gamma wr register.

      *                                  duty ^                 ONE HW LINEAR FADE
      *                                       |
      *                                       |
      *                                       |
      *                                       |
      *     start_duty + scale * n = end_duty |. . . . . . . . . . . . . . . . . . . . . . . . . .+-
      *                                       |                                                   |
      *                                       |                                                   |
      *                                       |                                          +--------+
      *                                       |                                          |        .
      *                                       |                                          |        .
      *                                       |                                   -------+        .
      *                                       |                                  .                .
      *                                       |                                .                  .
      *                                       |                              .                    .
      *                                       |                            .                      .
      *                                 ^ --- |. . . . . . . . . .+--------                       .
      *                            scale|     |                   |                               .
      *                                 |     |                   |                               .
      *                                 v --- |. . . . .+---------+                               .
      *                                       |         |         .                               .
      *                                       |         |         .                               .
      *                            start_duty +---------+         .                               .
      *                                       |         .         .                               .
      *                                       |         .         .                               .
      *                                       +----------------------------------------------------------->
      *                                                                                                  PWM cycle
      *                                       |         |         |                               |
      *                                       | 1 step  | 1 step  |                               |
      *                                       |<------->|<------->|                               |
      *                                       | m cycles  m cycles                                |
      *                                       |                                                   |
      *                                       <--------------------------------------------------->
      *                                                           n total steps
      *                                                          cycles = m * n
      *

  备注

  Be aware of the maximum value available on each element

  Public Members

  uint32_t dir

    Duty change direction. Set 1 as increase, 0 as decrease

  uint32_t cycle_num

    Number of PWM cycles of each step [0, 2**SOC_LEDC_FADE_PARAMS_BIT_WIDTH-1]

  uint32_t scale

    Duty change of each step [0, 2**SOC_LEDC_FADE_PARAMS_BIT_WIDTH-1]

  uint32_t step_num

    Total number of steps in one hardware fade [0, 2**SOC_LEDC_FADE_PARAMS_BIT_WIDTH-1]

### Macros

LEDC_ERR_DUTY

LEDC_ERR_VAL

### Type Definitions

typedef intr_handle_t ledc_isr_handle_t

typedef bool (*ledc_cb_t)(const ledc_cb_param_t *param, void *user_arg)

  Type of LEDC event callback.

  Param param:

    LEDC callback parameter

  Param user_arg:

    User registered data

  Return:

    Whether a high priority task has been waken up by this function

### Enumerations

enum ledc_sleep_mode_t

  Strategies to be applied to the LEDC channel during system Light-sleep period.

  Values:

  enumerator LEDC_SLEEP_MODE_NO_ALIVE_NO_PD

    The default mode: no LEDC output, and no power off the LEDC power domain.

  enumerator LEDC_SLEEP_MODE_NO_ALIVE_ALLOW_PD

    The low-power-consumption mode: no LEDC output, and allow to power off the LEDC power domain. This can save power, but at the expense of more RAM being consumed to save register context. This option is only available on targets that support TOP domain to be powered down.

  enumerator LEDC_SLEEP_MODE_KEEP_ALIVE

    The high-power-consumption mode: keep LEDC output when the system enters Light-sleep.

  enumerator LEDC_SLEEP_MODE_INVALID

    Invalid LEDC sleep mode strategy

enum ledc_cb_event_t

  LEDC callback event type.

  Values:

  enumerator LEDC_FADE_END_EVT

    LEDC fade end event

### Header File

- components/esp_hal_ledc/include/hal/ledc_types.h

- This header file can be included with:

  >     #include "hal/ledc_types.h"

- This header file is a part of the API provided by the `esp_hal_ledc` component. To declare that your component depends on `esp_hal_ledc`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_hal_ledc

  > or

  >     PRIV_REQUIRES esp_hal_ledc

### Type Definitions

typedef soc_periph_ledc_clk_src_legacy_t ledc_clk_cfg_t

  LEDC clock source configuration struct.

  In theory, the following enumeration shall be placed in LEDC driver's header. However, as the next enumeration, `ledc_clk_src_t`, makes the use of some of these values and to avoid mutual inclusion of the headers, we must define it here.

### Enumerations

enum ledc_mode_t

  Values:

  enumerator LEDC_LOW_SPEED_MODE

    LEDC low speed speed_mode

  enumerator LEDC_SPEED_MODE_MAX

    LEDC speed limit

enum ledc_intr_type_t

  Values:

  enumerator LEDC_INTR_DISABLE

    Disable LEDC interrupt

  enumerator LEDC_INTR_FADE_END

    Enable LEDC interrupt

  enumerator LEDC_INTR_MAX

enum ledc_duty_direction_t

  Values:

  enumerator LEDC_DUTY_DIR_DECREASE

    LEDC duty decrease direction

  enumerator LEDC_DUTY_DIR_INCREASE

    LEDC duty increase direction

  enumerator LEDC_DUTY_DIR_MAX

enum ledc_slow_clk_sel_t

  LEDC global clock sources.

  Values:

  enumerator LEDC_SLOW_CLK_RC_FAST

    LEDC low speed timer clock source is RC_FAST clock

  enumerator LEDC_SLOW_CLK_PLL_DIV

    LEDC low speed timer clock source is a PLL_DIV clock

  enumerator LEDC_SLOW_CLK_XTAL

    LEDC low speed timer clock source XTAL clock

enum ledc_clk_src_t

  LEDC timer-specific clock sources.

  Note: Setting numeric values to match ledc_clk_cfg_t values are a hack to avoid collision with LEDC_AUTO_CLK in the driver, as these enums have very similar names and user may pass one of these by mistake.

  Values:

  enumerator LEDC_SCLK

    Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from LEDC_CLK_SEL

enum ledc_timer_t

  Values:

  enumerator LEDC_TIMER_0

    LEDC timer 0

  enumerator LEDC_TIMER_1

    LEDC timer 1

  enumerator LEDC_TIMER_2

    LEDC timer 2

  enumerator LEDC_TIMER_3

    LEDC timer 3

  enumerator LEDC_TIMER_MAX

enum ledc_channel_t

  Values:

  enumerator LEDC_CHANNEL_0

    LEDC channel 0

  enumerator LEDC_CHANNEL_1

    LEDC channel 1

  enumerator LEDC_CHANNEL_2

    LEDC channel 2

  enumerator LEDC_CHANNEL_3

    LEDC channel 3

  enumerator LEDC_CHANNEL_4

    LEDC channel 4

  enumerator LEDC_CHANNEL_5

    LEDC channel 5

  enumerator LEDC_CHANNEL_6

    LEDC channel 6

  enumerator LEDC_CHANNEL_7

    LEDC channel 7

  enumerator LEDC_CHANNEL_MAX

enum ledc_timer_bit_t

  Values:

  enumerator LEDC_TIMER_1_BIT

    LEDC PWM duty resolution of 1 bits

  enumerator LEDC_TIMER_2_BIT

    LEDC PWM duty resolution of 2 bits

  enumerator LEDC_TIMER_3_BIT

    LEDC PWM duty resolution of 3 bits

  enumerator LEDC_TIMER_4_BIT

    LEDC PWM duty resolution of 4 bits

  enumerator LEDC_TIMER_5_BIT

    LEDC PWM duty resolution of 5 bits

  enumerator LEDC_TIMER_6_BIT

    LEDC PWM duty resolution of 6 bits

  enumerator LEDC_TIMER_7_BIT

    LEDC PWM duty resolution of 7 bits

  enumerator LEDC_TIMER_8_BIT

    LEDC PWM duty resolution of 8 bits

  enumerator LEDC_TIMER_9_BIT

    LEDC PWM duty resolution of 9 bits

  enumerator LEDC_TIMER_10_BIT

    LEDC PWM duty resolution of 10 bits

  enumerator LEDC_TIMER_11_BIT

    LEDC PWM duty resolution of 11 bits

  enumerator LEDC_TIMER_12_BIT

    LEDC PWM duty resolution of 12 bits

  enumerator LEDC_TIMER_13_BIT

    LEDC PWM duty resolution of 13 bits

  enumerator LEDC_TIMER_14_BIT

    LEDC PWM duty resolution of 14 bits

  enumerator LEDC_TIMER_15_BIT

    LEDC PWM duty resolution of 15 bits

  enumerator LEDC_TIMER_16_BIT

    LEDC PWM duty resolution of 16 bits

  enumerator LEDC_TIMER_17_BIT

    LEDC PWM duty resolution of 17 bits

  enumerator LEDC_TIMER_18_BIT

    LEDC PWM duty resolution of 18 bits

  enumerator LEDC_TIMER_19_BIT

    LEDC PWM duty resolution of 19 bits

  enumerator LEDC_TIMER_20_BIT

    LEDC PWM duty resolution of 20 bits

  enumerator LEDC_TIMER_BIT_MAX

enum ledc_fade_mode_t

  Values:

  enumerator LEDC_FADE_NO_WAIT

    LEDC fade function will return immediately

  enumerator LEDC_FADE_WAIT_DONE

    LEDC fade function will block until fading to the target duty

  enumerator LEDC_FADE_MAX

enum ledc_channel_etm_task_type_t

  LEDC channel related specific tasks that supported by the ETM module.

  Values:

  enumerator LEDC_CHANNEL_ETM_TASK_FADE_SCALE_UPDATE

    Update newly configured scale for the fade on the channel

  enumerator LEDC_CHANNEL_ETM_TASK_SIG_OUT_DIS

    Disable signal output on the channel

  enumerator LEDC_CHANNEL_ETM_TASK_OVF_CNT_RST

    Reset channel's timer overflow counter

  enumerator LEDC_CHANNEL_ETM_TASK_FADE_RESTART
  enumerator LEDC_CHANNEL_ETM_TASK_FADE_PAUSE

    Pause fading on the channel

  enumerator LEDC_CHANNEL_ETM_TASK_FADE_RESUME

    Resume fading on the channel

  enumerator LEDC_CHANNEL_ETM_TASK_MAX

enum ledc_timer_etm_task_type_t

  LEDC timer related specific tasks that supported by the ETM module.

  Values:

  enumerator LEDC_TIMER_ETM_TASK_RST

    Reset the timer When timer is reset, a timer overflow equivalent signal is sent to the channel, so any newly configured parameter is able to get updated This is not the case on C6/H2/P4/C5/H4/H21, on such targets, no timer overflow equivalent signal is sent to the channel, i.e. newly configured parameter is not able to get updated when this ETM task is triggered

  enumerator LEDC_TIMER_ETM_TASK_RESUME

    Resume the timer Note that the ETM timer pause/resume task must be used in pair Pause by ETM task and resume by calling `ledc_timer_resume` is not allowed, vice versa

  enumerator LEDC_TIMER_ETM_TASK_PAUSE

    Pause the timer

  enumerator LEDC_TIMER_ETM_TASK_MAX

enum ledc_channel_etm_event_type_t

  LEDC channel related specific events that supported by the ETM module.

  Values:

  enumerator LEDC_CHANNEL_ETM_EVENT_FADE_END

    Channel fading ended

  enumerator LEDC_CHANNEL_ETM_EVENT_REACH_MAX_OVF_CNT

    Channel has reached the maximum timer overflow count The maximum overflow count value can be set with `ledc_channel_configure_maximum_timer_ovf_cnt`

  enumerator LEDC_CHANNEL_ETM_EVENT_MAX

enum ledc_timer_etm_event_type_t

  LEDC timer related specific events that supported by the ETM module.

  Values:

  enumerator LEDC_TIMER_ETM_EVENT_OVF

    Timer overflow happened

  enumerator LEDC_TIMER_ETM_EVENT_MAX

### Header File

- components/esp_driver_ledc/include/driver/ledc_etm.h

- This header file can be included with:

  >     #include "driver/ledc_etm.h"

- This header file is a part of the API provided by the `esp_driver_ledc` component. To declare that your component depends on `esp_driver_ledc`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_driver_ledc

  > or

  >     PRIV_REQUIRES esp_driver_ledc

### Functions

esp_err_t ledc_timer_new_etm_event(ledc_mode_t speed_mode, ledc_timer_t timer_sel, const ledc_timer_etm_event_config_t *config, esp_etm_event_handle_t *out_event)

  Get the ETM timer event for LEDC.

  备注

  The created ETM event object can be deleted later by calling `esp_etm_del_event`

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode

    - timer_sel -- [in] LEDC timer index, select from ledc_timer_t

    - config -- [in] LEDC timer ETM event configuration

    - out_event -- [out] Returned ETM event handle

  返回:

    - ESP_OK: Get ETM event successfully

    - ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument

    - ESP_ERR_NO_MEM: Get ETM event failed because of no memory

esp_err_t ledc_channel_new_etm_event(ledc_mode_t speed_mode, ledc_channel_t channel, const ledc_channel_etm_event_config_t *config, esp_etm_event_handle_t *out_event)

  Get the ETM channel event for LEDC.

  备注

  The created ETM event object can be deleted later by calling `esp_etm_del_event`

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode

    - channel -- [in] LEDC channel index, select from ledc_channel_t

    - config -- [in] LEDC channel ETM event configuration

    - out_event -- [out] Returned ETM event handle

  返回:

    - ESP_OK: Get ETM event successfully

    - ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument

    - ESP_ERR_NO_MEM: Get ETM event failed because of no memory

esp_err_t ledc_timer_new_etm_task(ledc_mode_t speed_mode, ledc_timer_t timer_sel, const ledc_timer_etm_task_config_t *config, esp_etm_task_handle_t *out_task)

  Get the ETM timer task for LEDC.

  备注

  The created ETM task object can be deleted later by calling `esp_etm_del_task`

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode

    - timer_sel -- [in] LEDC timer index, select from ledc_timer_t

    - config -- [in] LEDC timer ETM task configuration

    - out_task -- [out] Returned ETM task handle

  返回:

    - ESP_OK: Get ETM task successfully

    - ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument

    - ESP_ERR_NO_MEM: Get ETM task failed because of no memory

esp_err_t ledc_channel_new_etm_task(ledc_mode_t speed_mode, ledc_channel_t channel, const ledc_channel_etm_task_config_t *config, esp_etm_task_handle_t *out_task)

  Get the ETM channel task for LEDC.

  备注

  The created ETM task object can be deleted later by calling `esp_etm_del_task`

  参数:

    - speed_mode -- [in] Select the LEDC channel group with specified speed mode

    - channel -- [in] LEDC channel index, select from ledc_channel_t

    - config -- [in] LEDC channel ETM task configuration

    - out_task -- [out] Returned ETM task handle

  返回:

    - ESP_OK: Get ETM task successfully

    - ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument

    - ESP_ERR_NO_MEM: Get ETM task failed because of no memory

### Structures

struct ledc_timer_etm_event_config_t

  LEDC timer ETM event configuration.

  Public Members

  ledc_timer_etm_event_type_t event_type

    LEDC timer ETM event type

struct ledc_channel_etm_event_config_t

  LEDC channel ETM event configuration.

  Public Members

  ledc_channel_etm_event_type_t event_type

    LEDC channel ETM event type

struct ledc_timer_etm_task_config_t

  LEDC timer ETM task configuration.

  Public Members

  ledc_timer_etm_task_type_t task_type

    LEDC timer ETM task type

struct ledc_channel_etm_task_config_t

  LEDC channel ETM task configuration.

  Public Members

  ledc_channel_etm_task_type_t task_type

    LEDC channel ETM task type

此文档对您有帮助吗？

- 反馈已收到，谢谢！
- 如果您有其他意见，欢迎填写乐鑫文档反馈表。

- 我们重视您的反馈。
- 您可以填写乐鑫文档反馈表告诉我们如何改进该文档。