13 ESP32PWM(
int gpio_num, ledc_channel_t channel, ledc_timer_t timer = LEDC_TIMER_0,
14 ledc_timer_bit_t resolution =
static_cast<ledc_timer_bit_t
>(
15 (
static_cast<uint8_t
>(LEDC_TIMER_BIT_MAX) - 1)))
16 : gpio_num_(gpio_num),
19 resolution_(resolution),
20 max_duty_((1 << resolution) - 1)
22 ledc_channel_config_t channel_conf = {};
23 channel_conf.gpio_num = gpio_num_;
24 channel_conf.speed_mode =
static_cast<ledc_mode_t
>(0);
25 channel_conf.channel = channel_;
26 channel_conf.intr_type = LEDC_INTR_DISABLE;
27 channel_conf.timer_sel = timer_;
28 channel_conf.duty = 0;
29 channel_conf.hpoint = 0;
31 auto err = ledc_channel_config(&channel_conf);
44 else if (value > 1.0f)
49 uint32_t duty =
static_cast<uint32_t
>(max_duty_ * value);
50 esp_err_t err = ledc_set_duty(
static_cast<ledc_mode_t
>(0), channel_, duty);
51 if (err != ESP_OK)
return ErrorCode::FAILED;
53 err = ledc_update_duty(
static_cast<ledc_mode_t
>(0), channel_);
54 return (err == ESP_OK) ? ErrorCode::OK : ErrorCode::FAILED;
61 return ErrorCode::ARG_ERR;
64 ledc_timer_config_t timer_conf = {};
65 timer_conf.speed_mode =
static_cast<ledc_mode_t
>(0);
66 timer_conf.duty_resolution = resolution_;
67 timer_conf.timer_num = timer_;
69 timer_conf.clk_cfg = LEDC_AUTO_CLK;
71 esp_err_t err = ledc_timer_config(&timer_conf);
72 if (err != ESP_OK)
return ErrorCode::INIT_ERR;
74 max_duty_ = (1 << resolution_) - 1;
80 esp_err_t err = ledc_update_duty(
static_cast<ledc_mode_t
>(0), channel_);
81 return (err == ESP_OK) ? ErrorCode::OK : ErrorCode::FAILED;
86 esp_err_t err = ledc_stop(
static_cast<ledc_mode_t
>(0), channel_, 0);
87 return (err == ESP_OK) ? ErrorCode::OK : ErrorCode::FAILED;
92 ledc_channel_t channel_;
94 ledc_timer_bit_t resolution_;