ESPHome 2026.3.0
Loading...
Searching...
No Matches
ledc_output.cpp
Go to the documentation of this file.
1#include "ledc_output.h"
2#include "esphome/core/log.h"
3
4#ifdef USE_ESP32
5
6#include <driver/ledc.h>
7#include <cinttypes>
8#include <esp_private/periph_ctrl.h>
9#if !defined(SOC_LEDC_SUPPORT_FADE_STOP)
10#include <hal/ledc_ll.h>
11#endif
12
13#define CLOCK_FREQUENCY 80e6f
14
15#ifdef SOC_LEDC_SUPPORT_APB_CLOCK
16#define DEFAULT_CLK LEDC_USE_APB_CLK
17#else
18#define DEFAULT_CLK LEDC_AUTO_CLK
19#endif
20
21static const uint8_t SETUP_ATTEMPT_COUNT_MAX = 5;
22
23namespace esphome::ledc {
24
25static const char *const TAG = "ledc.output";
26static bool ledc_peripheral_reset_done = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
27
28static const int MAX_RES_BITS = LEDC_TIMER_BIT_MAX - 1;
29#if SOC_LEDC_SUPPORT_HS_MODE
30// Only ESP32 has LEDC_HIGH_SPEED_MODE
31inline ledc_mode_t get_speed_mode(uint8_t channel) { return channel < 8 ? LEDC_HIGH_SPEED_MODE : LEDC_LOW_SPEED_MODE; }
32#else
33// S2, C3, S3 only support LEDC_LOW_SPEED_MODE
34// See
35// https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/api-reference/peripherals/ledc.html#functionality-overview
36inline ledc_mode_t get_speed_mode(uint8_t) { return LEDC_LOW_SPEED_MODE; }
37#endif
38
39#if !defined(SOC_LEDC_SUPPORT_FADE_STOP)
40// Classic ESP32 (currently the only target without SOC_LEDC_SUPPORT_FADE_STOP) can block in
41// ledc_ll_set_duty_start() while duty_start is set. We check the same conf1.duty_start bit here
42// to defer updates and avoid entering IDF's unbounded wait loop.
43//
44// This intentionally depends on the classic ESP32 LEDC register layout used by IDF's own LL HAL.
45// If another target without SOC_LEDC_SUPPORT_FADE_STOP is introduced, revisit this helper.
46static_assert(
47#if defined(CONFIG_IDF_TARGET_ESP32)
48 true,
49#else
50 false,
51#endif
52 "LEDC duty_start pending check assumes classic ESP32 register layout; "
53 "re-evaluate for this target");
54
55static bool ledc_duty_update_pending(ledc_mode_t speed_mode, ledc_channel_t chan_num) {
56 auto *hw = LEDC_LL_GET_HW();
57 return hw->channel_group[speed_mode].channel[chan_num].conf1.duty_start != 0;
58}
59#endif
60
61float ledc_max_frequency_for_bit_depth(uint8_t bit_depth) {
62 return static_cast<float>(CLOCK_FREQUENCY) / static_cast<float>(1 << bit_depth);
63}
64
65float ledc_min_frequency_for_bit_depth(uint8_t bit_depth, bool low_frequency) {
66 const float max_div_num = ((1 << MAX_RES_BITS) - 1) / (low_frequency ? 32.0f : 256.0f);
67 return static_cast<float>(CLOCK_FREQUENCY) / (max_div_num * static_cast<float>(1 << bit_depth));
68}
69
70optional<uint8_t> ledc_bit_depth_for_frequency(float frequency) {
71 ESP_LOGV(TAG, "Calculating resolution bit-depth for frequency %f", frequency);
72 for (int i = MAX_RES_BITS; i >= 1; i--) {
73 const float min_frequency = ledc_min_frequency_for_bit_depth(i, (frequency < 100));
74 const float max_frequency = ledc_max_frequency_for_bit_depth(i);
75 if (min_frequency <= frequency && frequency <= max_frequency) {
76 ESP_LOGV(TAG, "Resolution calculated as %d", i);
77 return i;
78 }
79 }
80 return {};
81}
82
83esp_err_t configure_timer_frequency(ledc_mode_t speed_mode, ledc_timer_t timer_num, ledc_channel_t chan_num,
84 uint8_t channel, uint8_t &bit_depth, float frequency) {
85 auto bit_depth_opt = ledc_bit_depth_for_frequency(frequency);
86 bit_depth = bit_depth_opt.value_or(0);
87 if (bit_depth < 1) {
88 ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", frequency);
89 }
90
91 ledc_timer_config_t timer_conf{};
92 timer_conf.speed_mode = speed_mode;
93 timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(bit_depth);
94 timer_conf.timer_num = timer_num;
95 timer_conf.freq_hz = (uint32_t) frequency;
96 timer_conf.clk_cfg = DEFAULT_CLK;
97
98 // Configure the time with fallback in case of error
99 int attempt_count_max = SETUP_ATTEMPT_COUNT_MAX;
100 esp_err_t init_result = ESP_FAIL;
101 while (attempt_count_max > 0 && init_result != ESP_OK) {
102 init_result = ledc_timer_config(&timer_conf);
103 if (init_result != ESP_OK) {
104 ESP_LOGW(TAG, "Unable to initialize timer with frequency %.1f and bit depth of %u", frequency, bit_depth);
105 if (bit_depth <= 1) {
106 break;
107 }
108 // try again with a lower bit depth
109 timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(--bit_depth);
110 }
111 attempt_count_max--;
112 }
113
114 return init_result;
115}
116
117constexpr int ledc_angle_to_htop(float angle, uint8_t bit_depth) {
118 return static_cast<int>(angle * ((1U << bit_depth) - 1) / 360.0f);
119}
120
122 if (!this->initialized_) {
123 ESP_LOGW(TAG, "Not yet initialized");
124 return;
125 }
126
127 if (this->pin_->is_inverted())
128 state = 1.0f - state;
129
130 this->duty_ = state;
131 const uint32_t max_duty = (uint32_t(1) << this->bit_depth_) - 1;
132 const float duty_rounded = roundf(state * max_duty);
133 auto duty = static_cast<uint32_t>(duty_rounded);
134 if (duty == this->last_duty_) {
135 return;
136 }
137
138 ESP_LOGV(TAG, "Setting duty: %" PRIu32 " on channel %u", duty, this->channel_);
139 auto speed_mode = get_speed_mode(this->channel_);
140 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
141 int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
142 if (duty == max_duty) {
143 ledc_stop(speed_mode, chan_num, 1);
144 this->last_duty_ = duty;
145 } else if (duty == 0) {
146 ledc_stop(speed_mode, chan_num, 0);
147 this->last_duty_ = duty;
148 } else {
149#if !defined(SOC_LEDC_SUPPORT_FADE_STOP)
150 if (ledc_duty_update_pending(speed_mode, chan_num)) {
151 ESP_LOGV(TAG, "Skipping LEDC duty update on channel %u while previous duty_start is still set", this->channel_);
152 return;
153 }
154#endif
155 ledc_set_duty_with_hpoint(speed_mode, chan_num, duty, hpoint);
156 ledc_update_duty(speed_mode, chan_num);
157 this->last_duty_ = duty;
158 }
159}
160
162 if (!ledc_peripheral_reset_done) {
163 ESP_LOGV(TAG, "Resetting LEDC peripheral to clear stale state after reboot");
164 periph_module_reset(PERIPH_LEDC_MODULE);
165 ledc_peripheral_reset_done = true;
166 }
167
168 auto speed_mode = get_speed_mode(this->channel_);
169 auto timer_num = static_cast<ledc_timer_t>((this->channel_ % 8) / 2);
170 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
171
172 esp_err_t timer_init_result =
173 configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
174
175 if (timer_init_result != ESP_OK) {
176 ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
177 this->status_set_error();
178 return;
179 }
180 int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
181
182 ESP_LOGV(TAG, "Configured frequency %f with bit depth %u, angle %.1f° hpoint %u", this->frequency_, this->bit_depth_,
183 this->phase_angle_, hpoint);
184
185 ledc_channel_config_t chan_conf{};
186 chan_conf.gpio_num = this->pin_->get_pin();
187 chan_conf.speed_mode = speed_mode;
188 chan_conf.channel = chan_num;
189 chan_conf.intr_type = LEDC_INTR_DISABLE;
190 chan_conf.timer_sel = timer_num;
191 chan_conf.duty = this->inverted_ == this->pin_->is_inverted() ? 0 : (1U << this->bit_depth_);
192 chan_conf.hpoint = hpoint;
193 ledc_channel_config(&chan_conf);
194 this->initialized_ = true;
195 this->status_clear_error();
196}
197
199 ESP_LOGCONFIG(TAG,
200 "Output:\n"
201 " Channel: %u\n"
202 " PWM Frequency: %.1f Hz\n"
203 " Phase angle: %.1f°\n"
204 " Bit depth: %u",
205 this->channel_, this->frequency_, this->phase_angle_, this->bit_depth_);
206 LOG_PIN(" Pin ", this->pin_);
207 ESP_LOGV(TAG,
208 " Max frequency for bit depth: %f\n"
209 " Min frequency for bit depth: %f\n"
210 " Max frequency for bit depth-1: %f\n"
211 " Min frequency for bit depth-1: %f\n"
212 " Max frequency for bit depth+1: %f\n"
213 " Min frequency for bit depth+1: %f\n"
214 " Max res bits: %d\n"
215 " Clock frequency: %f",
221 ledc_min_frequency_for_bit_depth(this->bit_depth_ + 1, (this->frequency_ < 100)), MAX_RES_BITS,
222 CLOCK_FREQUENCY);
223}
224
226 auto bit_depth_opt = ledc_bit_depth_for_frequency(frequency);
227 if (!bit_depth_opt.has_value()) {
228 ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", this->frequency_);
229 this->status_set_error();
230 }
231 this->bit_depth_ = bit_depth_opt.value_or(8);
232 this->frequency_ = frequency;
233
234 if (!this->initialized_) {
235 ESP_LOGW(TAG, "Not yet initialized");
236 return;
237 }
238
239 auto speed_mode = get_speed_mode(this->channel_);
240 auto timer_num = static_cast<ledc_timer_t>((this->channel_ % 8) / 2);
241 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
242
243 esp_err_t timer_init_result =
244 configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
245
246 if (timer_init_result != ESP_OK) {
247 ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
248 this->status_set_error();
249 return;
250 }
251
252 this->status_clear_error();
253
254 // re-apply duty
255 this->last_duty_ = UINT32_MAX;
256 this->write_state(this->duty_);
257}
258
259uint8_t next_ledc_channel = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
260
261} // namespace esphome::ledc
262
263#endif
uint16_le_t frequency
Definition bl0942.h:6
void status_clear_error()
Definition component.h:260
virtual uint8_t get_pin() const =0
virtual bool is_inverted() const =0
void update_frequency(float frequency) override
Dynamically change frequency at runtime.
void setup() override
Setup LEDC.
void write_state(float state) override
Override FloatOutput's write_state.
void dump_config() override
InternalGPIOPin * pin_
Definition ledc_output.h:36
bool state
Definition fan.h:2
esp_err_t configure_timer_frequency(ledc_mode_t speed_mode, ledc_timer_t timer_num, ledc_channel_t chan_num, uint8_t channel, uint8_t &bit_depth, float frequency)
uint8_t next_ledc_channel
optional< uint8_t > ledc_bit_depth_for_frequency(float frequency)
constexpr int ledc_angle_to_htop(float angle, uint8_t bit_depth)
float ledc_min_frequency_for_bit_depth(uint8_t bit_depth, bool low_frequency)
ledc_mode_t get_speed_mode(uint8_t channel)
float ledc_max_frequency_for_bit_depth(uint8_t bit_depth)
static void uint32_t