3#include "driver/ledc.h"
6#include "hal/ledc_hal.h"
17 ESP32PWM(
int gpio_num, ledc_channel_t channel, ledc_timer_t timer = LEDC_TIMER_0,
18 ledc_timer_bit_t resolution =
static_cast<ledc_timer_bit_t
>(
19 static_cast<uint8_t
>(LEDC_TIMER_BIT_MAX) - 1))
20 : gpio_num_(gpio_num),
23 speed_mode_(LEDC_LOW_SPEED_MODE),
24 resolution_(resolution),
25 max_duty_((1U << static_cast<uint8_t>(resolution_)) - 1U)
27 ledc_hal_init(&hal_, speed_mode_);
29 ledc_channel_config_t channel_conf = {};
30 channel_conf.gpio_num = gpio_num_;
31 channel_conf.speed_mode = speed_mode_;
32 channel_conf.channel = channel_;
33 channel_conf.intr_type = LEDC_INTR_DISABLE;
34 channel_conf.timer_sel = timer_;
35 channel_conf.duty = 0;
36 channel_conf.hpoint = 0;
38 const esp_err_t err = ledc_channel_config(&channel_conf);
51 else if (value > 1.0f)
56 const uint32_t duty =
static_cast<uint32_t
>(max_duty_ * value);
57 ledc_hal_set_duty_int_part(&hal_, channel_, duty);
58 ledc_hal_set_duty_start(&hal_, channel_);
59 ledc_hal_ls_channel_update(&hal_, channel_);
70 for (
int bits =
static_cast<int>(resolution_);
71 bits >=
static_cast<int>(LEDC_TIMER_1_BIT); --bits)
73 ledc_timer_config_t timer_conf = {};
74 timer_conf.speed_mode = speed_mode_;
75 timer_conf.duty_resolution =
static_cast<ledc_timer_bit_t
>(bits);
76 timer_conf.timer_num = timer_;
78 timer_conf.clk_cfg = LEDC_AUTO_CLK;
80 if (ledc_timer_config(&timer_conf) != ESP_OK)
85 resolution_ =
static_cast<ledc_timer_bit_t
>(bits);
86 ledc_hal_bind_channel_timer(&hal_, channel_, timer_);
87 ledc_hal_ls_timer_update(&hal_, timer_);
88 max_duty_ = (1U <<
static_cast<uint8_t
>(resolution_)) - 1U;
97 ledc_hal_set_sig_out_en(&hal_, channel_,
true);
98 ledc_hal_ls_channel_update(&hal_, channel_);
104 ledc_hal_set_idle_level(&hal_, channel_, 0);
105 ledc_hal_set_sig_out_en(&hal_, channel_,
false);
106 ledc_hal_ls_channel_update(&hal_, channel_);
112 ledc_channel_t channel_;
114 ledc_mode_t speed_mode_;
115 ledc_hal_context_t hal_{};
116 ledc_timer_bit_t resolution_;
ESP32 PWM driver implementation.
ErrorCode Enable() override
启用 PWM 输出 / Enables the PWM output.
ErrorCode SetConfig(Configuration config) override
配置 PWM 参数 / Configures the PWM settings.
ErrorCode SetDutyCycle(float value) override
设置 PWM 信号的占空比 / Sets the duty cycle of the PWM signal.
ESP32PWM(int gpio_num, ledc_channel_t channel, ledc_timer_t timer=LEDC_TIMER_0, ledc_timer_bit_t resolution=static_cast< ledc_timer_bit_t >(static_cast< uint8_t >(LEDC_TIMER_BIT_MAX) - 1))
Construct a PWM channel object.
ErrorCode Disable() override
禁用 PWM 输出 / Disables the PWM output.
PWM(脉冲宽度调制)控制的抽象基类。 Abstract base class for PWM (Pulse Width Modulation) control.
LibXR 命名空间 / LibXR namespace.
ErrorCode
定义错误码枚举 / Defines an enumeration for error codes
@ INIT_ERR
初始化错误 / Initialization error
@ OK
操作成功 / Operation successful
@ ARG_ERR
参数错误 / Argument error
PWM 配置参数 / Configuration parameters for PWM.
uint32_t frequency
PWM 信号的频率(Hz) / PWM signal frequency in Hz.