ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ledc_output.cpp
Go to the documentation of this file.
1#include "ledc_output.h"
2#include "ledc_duty.h"
3#include "esphome/core/log.h"
4
5#ifdef USE_ESP32
6
7#include <driver/gpio.h>
8#include <driver/ledc.h>
9#include <cinttypes>
10#include <esp_idf_version.h>
11#include <esp_private/periph_ctrl.h>
12#include <hal/ledc_ll.h>
13
14#define CLOCK_FREQUENCY 80e6f
15
16#ifdef SOC_LEDC_SUPPORT_APB_CLOCK
17#define DEFAULT_CLK LEDC_USE_APB_CLK
18#else
19#define DEFAULT_CLK LEDC_AUTO_CLK
20#endif
21
22static const uint8_t SETUP_ATTEMPT_COUNT_MAX = 5;
23
24namespace esphome::ledc {
25
26ESPHOME_LOG_TAG(TAG, "ledc.output");
27static bool ledc_peripheral_reset_done = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
28
29static const int MAX_RES_BITS = LEDC_TIMER_BIT_MAX - 1;
30#if SOC_LEDC_SUPPORT_HS_MODE
31// Only ESP32 has LEDC_HIGH_SPEED_MODE
32inline ledc_mode_t get_speed_mode(uint8_t channel) { return channel < 8 ? LEDC_HIGH_SPEED_MODE : LEDC_LOW_SPEED_MODE; }
33#else
34// S2, C3, S3 only support LEDC_LOW_SPEED_MODE
35// See
36// https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/api-reference/peripherals/ledc.html#functionality-overview
37inline ledc_mode_t get_speed_mode(uint8_t) { return LEDC_LOW_SPEED_MODE; }
38#endif
39
40#if defined(USE_LEDC_DITHERING) || !defined(SOC_LEDC_SUPPORT_FADE_STOP)
41static inline ledc_dev_t *ledc_get_hw() {
42#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 1, 0)
43 return LEDC_LL_GET_HW(0);
44#else
45 return LEDC_LL_GET_HW();
46#endif
47}
48#endif
49
50#ifdef USE_LEDC_DITHERING
51static void ledc_set_duty_fixed_point(ledc_mode_t speed_mode, ledc_channel_t chan_num, uint32_t duty) {
52 auto *hw = ledc_get_hw();
53 // Match each target's ledc_ll_set_duty_int_part(), but retain the four fractional bits.
54#if defined(USE_ESP32_VARIANT_ESP32C5) || defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32P4) || \
55 defined(USE_ESP32_VARIANT_ESP32S31)
56 hw->channel_group[speed_mode].channel[chan_num].duty_init.duty = duty;
57#else
58 hw->channel_group[speed_mode].channel[chan_num].duty.duty = duty;
59#endif
60}
61#endif
62
63#if !defined(SOC_LEDC_SUPPORT_FADE_STOP)
64// Classic ESP32 (currently the only target without SOC_LEDC_SUPPORT_FADE_STOP) can block in
65// ledc_ll_set_duty_start() while duty_start is set. We check the same conf1.duty_start bit here
66// to defer updates and avoid entering IDF's unbounded wait loop.
67//
68// This intentionally depends on the classic ESP32 LEDC register layout used by IDF's own LL HAL.
69// If another target without SOC_LEDC_SUPPORT_FADE_STOP is introduced, revisit this helper.
70static_assert(
71#if defined(CONFIG_IDF_TARGET_ESP32)
72 true,
73#else
74 false,
75#endif
76 "LEDC duty_start pending check assumes classic ESP32 register layout; "
77 "re-evaluate for this target");
78
79static bool ledc_duty_update_pending(ledc_mode_t speed_mode, ledc_channel_t chan_num) {
80 auto *hw = ledc_get_hw();
81 return hw->channel_group[speed_mode].channel[chan_num].conf1.duty_start != 0;
82}
83#endif
84
85float ledc_max_frequency_for_bit_depth(uint8_t bit_depth) {
86 return static_cast<float>(CLOCK_FREQUENCY) / static_cast<float>(1 << bit_depth);
87}
88
89float ledc_min_frequency_for_bit_depth(uint8_t bit_depth, bool low_frequency) {
90 const float max_div_num = ((1 << MAX_RES_BITS) - 1) / (low_frequency ? 32.0f : 256.0f);
91 return static_cast<float>(CLOCK_FREQUENCY) / (max_div_num * static_cast<float>(1 << bit_depth));
92}
93
94optional<uint8_t> ledc_bit_depth_for_frequency(float frequency) {
95 ESP_LOGV(TAG, "Calculating resolution bit-depth for frequency %f", frequency);
96 for (int i = MAX_RES_BITS; i >= 1; i--) {
97 const float min_frequency = ledc_min_frequency_for_bit_depth(i, (frequency < 100));
98 const float max_frequency = ledc_max_frequency_for_bit_depth(i);
99 if (min_frequency <= frequency && frequency <= max_frequency) {
100 ESP_LOGV(TAG, "Resolution calculated as %d", i);
101 return i;
102 }
103 }
104 return {};
105}
106
107esp_err_t configure_timer_frequency(ledc_mode_t speed_mode, ledc_timer_t timer_num, ledc_channel_t chan_num,
108 uint8_t channel, uint8_t &bit_depth, float frequency) {
109 auto bit_depth_opt = ledc_bit_depth_for_frequency(frequency);
110 bit_depth = bit_depth_opt.value_or(0);
111 if (bit_depth < 1) {
112 ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", frequency);
113 }
114
115 ledc_timer_config_t timer_conf{};
116 timer_conf.speed_mode = speed_mode;
117 timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(bit_depth);
118 timer_conf.timer_num = timer_num;
119 timer_conf.freq_hz = (uint32_t) frequency;
120 timer_conf.clk_cfg = DEFAULT_CLK;
121
122 // Configure the time with fallback in case of error
123 int attempt_count_max = SETUP_ATTEMPT_COUNT_MAX;
124 esp_err_t init_result = ESP_FAIL;
125 while (attempt_count_max > 0 && init_result != ESP_OK) {
126 init_result = ledc_timer_config(&timer_conf);
127 if (init_result != ESP_OK) {
128 ESP_LOGW(TAG, "Unable to initialize timer with frequency %.1f and bit depth of %u", frequency, bit_depth);
129 if (bit_depth <= 1) {
130 break;
131 }
132 // try again with a lower bit depth
133 timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(--bit_depth);
134 }
135 attempt_count_max--;
136 }
137
138 return init_result;
139}
140
141constexpr int ledc_angle_to_htop(float angle, uint8_t bit_depth) {
142 return static_cast<int>(angle * ((1U << bit_depth) - 1) / 360.0f);
143}
144
146 if (!this->initialized_) {
147 ESP_LOGW(TAG, "Not yet initialized");
148 return;
149 }
150
151 if (this->pin_->is_inverted())
152 state = 1.0f - state;
153
154 this->duty_ = state;
155 this->write_duty_();
156}
157
158void LEDCOutput::loop() { this->write_duty_(); }
159
161 uint8_t fractional_bits = 0;
162#ifdef USE_LEDC_DITHERING
163 fractional_bits = this->dithering_ ? 4 : 0;
164#endif
165 const uint32_t max_duty = full_scale_ticks(this->bit_depth_, fractional_bits);
166 const uint32_t duty = duty_to_ticks(this->duty_, this->bit_depth_, fractional_bits);
167 if (duty == this->last_duty_) {
168 this->status_clear_warning();
169 this->disable_loop();
170 return;
171 }
172
173 ESP_LOGV(TAG, "Setting duty: %" PRIu32 " on channel %u", duty, this->channel_);
174 auto speed_mode = get_speed_mode(this->channel_);
175 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
176 int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
177 esp_err_t err;
178 if (duty == max_duty) {
179 err = ledc_stop(speed_mode, chan_num, 1);
180 } else {
181#if !defined(SOC_LEDC_SUPPORT_FADE_STOP)
182 if (ledc_duty_update_pending(speed_mode, chan_num)) {
183 ESP_LOGV(TAG, "Deferring duty update on channel %u while previous duty_start is still set", this->channel_);
184 this->enable_loop();
185 return;
186 }
187#endif
188 // Zero takes this path too, not ledc_stop(): the update applies at the next PWM cycle,
189 // so the last servo pulse is not truncated into what the servo reads as a new position.
190 err = ledc_set_duty_with_hpoint(speed_mode, chan_num, duty >> fractional_bits, hpoint);
191#ifdef USE_LEDC_DITHERING
192 if (err == ESP_OK && this->dithering_) {
193 // IDF's integer setter clears the fractional bits. Restore them before latching the update.
194 ledc_set_duty_fixed_point(speed_mode, chan_num, duty);
195 }
196#endif
197 if (err == ESP_OK)
198 err = ledc_update_duty(speed_mode, chan_num);
199 }
200 if (err != ESP_OK) {
201 if (!this->status_has_warning()) {
202 ESP_LOGW(TAG, "Setting duty on channel %u failed: %s", this->channel_, esp_err_to_name(err));
203 }
204 this->status_set_warning();
205 this->enable_loop();
206 return;
207 }
208 this->last_duty_ = duty;
209 this->status_clear_warning();
210 this->disable_loop();
211}
212
214 this->disable_loop();
215 if (!ledc_peripheral_reset_done) {
216 ESP_LOGV(TAG, "Resetting LEDC peripheral to clear stale state after reboot");
217 // Skip under clang-tidy: the inlined HAL MMIO writes trip clang-analyzer-core.FixedAddressDereference
218#if !defined(CLANG_TIDY)
219#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 1, 0)
220 PERIPH_RCC_ATOMIC() { ledc_ll_reset_register(0); }
221#elif ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0) || \
222 (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0) && !defined(__PERIPH_CTRL_ALLOW_LEGACY_API))
223 // Also on the targets whose periph_module_reset() is an empty stub in ESP-IDF 5.x (P4, C5, C61, H4)
224 PERIPH_RCC_ATOMIC() {
225 ledc_ll_enable_reset_reg(true);
226 ledc_ll_enable_reset_reg(false);
227 }
228#else
229 periph_module_reset(PERIPH_LEDC_MODULE);
230#endif
231#endif
232 ledc_peripheral_reset_done = true;
233 }
234
235 auto speed_mode = get_speed_mode(this->channel_);
236 auto timer_num = static_cast<ledc_timer_t>((this->channel_ % 8) / 2);
237 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
238
239 esp_err_t timer_init_result =
240 configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
241
242 if (timer_init_result != ESP_OK) {
243 ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
244 this->status_set_error();
245 return;
246 }
247 int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
248
249 ESP_LOGV(TAG, "Configured frequency %f with bit depth %u, angle %.1f° hpoint %u", this->frequency_, this->bit_depth_,
250 this->phase_angle_, hpoint);
251
252 ledc_channel_config_t chan_conf{};
253 chan_conf.gpio_num = static_cast<gpio_num_t>(this->pin_->get_pin());
254 chan_conf.speed_mode = speed_mode;
255 chan_conf.channel = chan_num;
256#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0)
257 chan_conf.intr_type = LEDC_INTR_DISABLE;
258#endif
259 chan_conf.timer_sel = timer_num;
260 // Cache the physical off level before any runtime frequency change can reapply it.
261 this->duty_ = this->inverted_ == this->pin_->is_inverted() ? 0.0f : 1.0f;
262 chan_conf.duty = this->duty_ == 0.0f ? 0 : (1U << this->bit_depth_);
263 chan_conf.hpoint = hpoint;
264 ledc_channel_config(&chan_conf);
265 this->initialized_ = true;
266 this->status_clear_error();
267}
268
270 ESP_LOGCONFIG(TAG,
271 "Output:\n"
272 " Channel: %u\n"
273 " PWM Frequency: %.1f Hz\n"
274 " Phase angle: %.1f°\n"
275 " Bit depth: %u",
276 this->channel_, this->frequency_, this->phase_angle_, this->bit_depth_);
277#ifdef USE_LEDC_DITHERING
278 ESP_LOGCONFIG(TAG, " Hardware dithering: %u fractional bits", this->dithering_ ? 4 : 0);
279#endif
280 LOG_PIN(" Pin ", this->pin_);
281 ESP_LOGV(TAG,
282 " Max frequency for bit depth: %f\n"
283 " Min frequency for bit depth: %f\n"
284 " Max frequency for bit depth-1: %f\n"
285 " Min frequency for bit depth-1: %f\n"
286 " Max frequency for bit depth+1: %f\n"
287 " Min frequency for bit depth+1: %f\n"
288 " Max res bits: %d\n"
289 " Clock frequency: %f",
295 ledc_min_frequency_for_bit_depth(this->bit_depth_ + 1, (this->frequency_ < 100)), MAX_RES_BITS,
296 CLOCK_FREQUENCY);
297}
298
300 auto bit_depth_opt = ledc_bit_depth_for_frequency(frequency);
301 if (!bit_depth_opt.has_value()) {
302 ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", this->frequency_);
303 this->status_set_error();
304 }
305 this->bit_depth_ = bit_depth_opt.value_or(8);
306 this->frequency_ = frequency;
307
308 if (!this->initialized_) {
309 ESP_LOGW(TAG, "Not yet initialized");
310 return;
311 }
312
313 auto speed_mode = get_speed_mode(this->channel_);
314 auto timer_num = static_cast<ledc_timer_t>((this->channel_ % 8) / 2);
315 auto chan_num = static_cast<ledc_channel_t>(this->channel_ % 8);
316
317 esp_err_t timer_init_result =
318 configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
319
320 if (timer_init_result != ESP_OK) {
321 ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
322 this->status_set_error();
323 return;
324 }
325
326 this->status_clear_error();
327
328 // re-apply duty
329 this->last_duty_ = UINT32_MAX;
330 this->write_duty_();
331}
332
333uint8_t next_ledc_channel = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
334
335} // namespace esphome::ledc
336
337#endif
uint16_le_t frequency
Definition bl0942.h:6
void status_clear_error()
Definition component.h:315
void enable_loop()
Enable this component's loop.
Definition component.h:261
bool status_has_warning() const
Definition component.h:293
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:309
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:41
bool state
Definition fan.h:2
uint32_t full_scale_ticks(uint8_t bit_depth, uint8_t fractional_bits)
Ticks for a constant high output, one past the highest PWM level.
Definition ledc_duty.h:9
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)
uint32_t duty_to_ticks(float state, uint8_t bit_depth, uint8_t fractional_bits)
Convert a 0-1 duty to timer ticks, with fractional_bits extra bits for dithering.
Definition ledc_duty.h:14
ESPHOME_LOG_TAG(TAG, "ledc.output")
float ledc_max_frequency_for_bit_depth(uint8_t bit_depth)
static void uint32_t