ESPHome  2024.7.1
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 #ifdef USE_ARDUINO
7 #include <esp32-hal-ledc.h>
8 #endif
9 #include <driver/ledc.h>
10 
11 #define CLOCK_FREQUENCY 80e6f
12 
13 #ifdef USE_ARDUINO
14 #ifdef SOC_LEDC_SUPPORT_XTAL_CLOCK
15 #undef CLOCK_FREQUENCY
16 // starting with ESP32 Arduino 2.0.2, the 40MHz crystal is used as clock by default if supported
17 #define CLOCK_FREQUENCY 40e6f
18 #endif
19 #else
20 #ifdef SOC_LEDC_SUPPORT_APB_CLOCK
21 #define DEFAULT_CLK LEDC_USE_APB_CLK
22 #else
23 #define DEFAULT_CLK LEDC_AUTO_CLK
24 #endif
25 #endif
26 
27 static const uint8_t SETUP_ATTEMPT_COUNT_MAX = 5;
28 
29 namespace esphome {
30 namespace ledc {
31 
32 static const char *const TAG = "ledc.output";
33 
34 static const int MAX_RES_BITS = LEDC_TIMER_BIT_MAX - 1;
35 #ifdef USE_ESP_IDF
36 #if SOC_LEDC_SUPPORT_HS_MODE
37 // Only ESP32 has LEDC_HIGH_SPEED_MODE
38 inline ledc_mode_t get_speed_mode(uint8_t channel) { return channel < 8 ? LEDC_HIGH_SPEED_MODE : LEDC_LOW_SPEED_MODE; }
39 #else
40 // S2, C3, S3 only support LEDC_LOW_SPEED_MODE
41 // See
42 // https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/api-reference/peripherals/ledc.html#functionality-overview
43 inline ledc_mode_t get_speed_mode(uint8_t) { return LEDC_LOW_SPEED_MODE; }
44 #endif
45 #endif
46 
47 float ledc_max_frequency_for_bit_depth(uint8_t bit_depth) { return CLOCK_FREQUENCY / float(1 << bit_depth); }
48 
49 float ledc_min_frequency_for_bit_depth(uint8_t bit_depth, bool low_frequency) {
50  const float max_div_num = ((1 << MAX_RES_BITS) - 1) / (low_frequency ? 32.0f : 256.0f);
51  return CLOCK_FREQUENCY / (max_div_num * float(1 << bit_depth));
52 }
53 
55  ESP_LOGV(TAG, "Calculating resolution bit-depth for frequency %f", frequency);
56  for (int i = MAX_RES_BITS; i >= 1; i--) {
57  const float min_frequency = ledc_min_frequency_for_bit_depth(i, (frequency < 100));
58  const float max_frequency = ledc_max_frequency_for_bit_depth(i);
59  if (min_frequency <= frequency && frequency <= max_frequency) {
60  ESP_LOGV(TAG, "Resolution calculated as %d", i);
61  return i;
62  }
63  }
64  return {};
65 }
66 
67 #ifdef USE_ESP_IDF
68 esp_err_t configure_timer_frequency(ledc_mode_t speed_mode, ledc_timer_t timer_num, ledc_channel_t chan_num,
69  uint8_t channel, uint8_t &bit_depth, float frequency) {
70  bit_depth = *ledc_bit_depth_for_frequency(frequency);
71  if (bit_depth < 1) {
72  ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", frequency);
73  }
74 
75  ledc_timer_config_t timer_conf{};
76  timer_conf.speed_mode = speed_mode;
77  timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(bit_depth);
78  timer_conf.timer_num = timer_num;
79  timer_conf.freq_hz = (uint32_t) frequency;
80  timer_conf.clk_cfg = DEFAULT_CLK;
81 
82  // Configure the time with fallback in case of error
83  int attempt_count_max = SETUP_ATTEMPT_COUNT_MAX;
84  esp_err_t init_result = ESP_FAIL;
85  while (attempt_count_max > 0 && init_result != ESP_OK) {
86  init_result = ledc_timer_config(&timer_conf);
87  if (init_result != ESP_OK) {
88  ESP_LOGW(TAG, "Unable to initialize timer with frequency %.1f and bit depth of %u", frequency, bit_depth);
89  // try again with a lower bit depth
90  timer_conf.duty_resolution = static_cast<ledc_timer_bit_t>(--bit_depth);
91  }
92  attempt_count_max--;
93  }
94 
95  return init_result;
96 }
97 #endif
98 
99 #ifdef USE_ESP_IDF
100 constexpr int ledc_angle_to_htop(float angle, uint8_t bit_depth) {
101  return static_cast<int>(angle * ((1U << bit_depth) - 1) / 360.);
102 }
103 #endif // USE_ESP_IDF
104 
106  if (!initialized_) {
107  ESP_LOGW(TAG, "LEDC output hasn't been initialized yet!");
108  return;
109  }
110 
111  if (this->pin_->is_inverted())
112  state = 1.0f - state;
113 
114  this->duty_ = state;
115  const uint32_t max_duty = (uint32_t(1) << this->bit_depth_) - 1;
116  const float duty_rounded = roundf(state * max_duty);
117  auto duty = static_cast<uint32_t>(duty_rounded);
118 #ifdef USE_ARDUINO
119  ESP_LOGV(TAG, "Setting duty: %u on channel %u", duty, this->channel_);
120  ledcWrite(this->channel_, duty);
121 #endif
122 #ifdef USE_ESP_IDF
123  // ensure that 100% on is not 99.975% on
124  if ((duty == max_duty) && (max_duty != 1)) {
125  duty = max_duty + 1;
126  }
127  auto speed_mode = get_speed_mode(channel_);
128  auto chan_num = static_cast<ledc_channel_t>(channel_ % 8);
129  int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
130  ledc_set_duty_with_hpoint(speed_mode, chan_num, duty, hpoint);
131  ledc_update_duty(speed_mode, chan_num);
132 #endif
133 }
134 
136  ESP_LOGV(TAG, "Entering setup...");
137 #ifdef USE_ARDUINO
138  this->update_frequency(this->frequency_);
139  this->turn_off();
140  // Attach pin after setting default value
141  ledcAttachPin(this->pin_->get_pin(), this->channel_);
142 #endif
143 #ifdef USE_ESP_IDF
144  auto speed_mode = get_speed_mode(channel_);
145  auto timer_num = static_cast<ledc_timer_t>((channel_ % 8) / 2);
146  auto chan_num = static_cast<ledc_channel_t>(channel_ % 8);
147 
148  esp_err_t timer_init_result =
149  configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
150 
151  if (timer_init_result != ESP_OK) {
152  ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
153  this->status_set_error();
154  return;
155  }
156  int hpoint = ledc_angle_to_htop(this->phase_angle_, this->bit_depth_);
157 
158  ESP_LOGV(TAG, "Configured frequency %f with a bit depth of %u bits", this->frequency_, this->bit_depth_);
159  ESP_LOGV(TAG, "Angle of %.1f° results in hpoint %u", this->phase_angle_, hpoint);
160 
161  ledc_channel_config_t chan_conf{};
162  chan_conf.gpio_num = pin_->get_pin();
163  chan_conf.speed_mode = speed_mode;
164  chan_conf.channel = chan_num;
165  chan_conf.intr_type = LEDC_INTR_DISABLE;
166  chan_conf.timer_sel = timer_num;
167  chan_conf.duty = inverted_ == pin_->is_inverted() ? 0 : (1U << bit_depth_);
168  chan_conf.hpoint = hpoint;
169  ledc_channel_config(&chan_conf);
170  initialized_ = true;
171  this->status_clear_error();
172 #endif
173 }
174 
176  ESP_LOGCONFIG(TAG, "LEDC Output:");
177  LOG_PIN(" Pin ", this->pin_);
178  ESP_LOGCONFIG(TAG, " LEDC Channel: %u", this->channel_);
179  ESP_LOGCONFIG(TAG, " PWM Frequency: %.1f Hz", this->frequency_);
180  ESP_LOGCONFIG(TAG, " Phase angle: %.1f°", this->phase_angle_);
181  ESP_LOGCONFIG(TAG, " Bit depth: %u", this->bit_depth_);
182  ESP_LOGV(TAG, " Max frequency for bit depth: %f", ledc_max_frequency_for_bit_depth(this->bit_depth_));
183  ESP_LOGV(TAG, " Min frequency for bit depth: %f",
185  ESP_LOGV(TAG, " Max frequency for bit depth-1: %f", ledc_max_frequency_for_bit_depth(this->bit_depth_ - 1));
186  ESP_LOGV(TAG, " Min frequency for bit depth-1: %f",
187  ledc_min_frequency_for_bit_depth(this->bit_depth_ - 1, (this->frequency_ < 100)));
188  ESP_LOGV(TAG, " Max frequency for bit depth+1: %f", ledc_max_frequency_for_bit_depth(this->bit_depth_ + 1));
189  ESP_LOGV(TAG, " Min frequency for bit depth+1: %f",
190  ledc_min_frequency_for_bit_depth(this->bit_depth_ + 1, (this->frequency_ < 100)));
191  ESP_LOGV(TAG, " Max res bits: %d", MAX_RES_BITS);
192  ESP_LOGV(TAG, " Clock frequency: %f", CLOCK_FREQUENCY);
193 }
194 
196  auto bit_depth_opt = ledc_bit_depth_for_frequency(frequency);
197  if (!bit_depth_opt.has_value()) {
198  ESP_LOGE(TAG, "Frequency %f can't be achieved with any bit depth", this->frequency_);
199  this->status_set_error();
200  }
201  this->bit_depth_ = bit_depth_opt.value_or(8);
202  this->frequency_ = frequency;
203 #ifdef USE_ARDUINO
204  ESP_LOGV(TAG, "Using Arduino API - Trying to define channel, frequency and bit depth...");
205  u_int32_t configured_frequency = 0;
206 
207  // Configure LEDC channel, frequency and bit depth with fallback
208  int attempt_count_max = SETUP_ATTEMPT_COUNT_MAX;
209  while (attempt_count_max > 0 && configured_frequency == 0) {
210  ESP_LOGV(TAG, "Trying initialize channel %u with frequency %.1f and bit depth of %u...", this->channel_,
211  this->frequency_, this->bit_depth_);
212  configured_frequency = ledcSetup(this->channel_, frequency, this->bit_depth_);
213  if (configured_frequency != 0) {
214  initialized_ = true;
215  this->status_clear_error();
216  ESP_LOGV(TAG, "Configured frequency: %u with bit depth: %u", configured_frequency, this->bit_depth_);
217  } else {
218  ESP_LOGW(TAG, "Unable to initialize channel %u with frequency %.1f and bit depth of %u", this->channel_,
219  this->frequency_, this->bit_depth_);
220  // try again with a lower bit depth
221  this->bit_depth_--;
222  }
223  attempt_count_max--;
224  }
225 
226  if (configured_frequency == 0) {
227  ESP_LOGE(TAG, "Permanently failed to initialize channel %u with frequency %.1f and bit depth of %u", this->channel_,
228  this->frequency_, this->bit_depth_);
229  this->status_set_error();
230  return;
231  }
232 
233 #endif // USE_ARDUINO
234 #ifdef USE_ESP_IDF
235  if (!initialized_) {
236  ESP_LOGW(TAG, "LEDC output hasn't been initialized yet!");
237  return;
238  }
239 
240  auto speed_mode = get_speed_mode(channel_);
241  auto timer_num = static_cast<ledc_timer_t>((channel_ % 8) / 2);
242  auto chan_num = static_cast<ledc_channel_t>(channel_ % 8);
243 
244  esp_err_t timer_init_result =
245  configure_timer_frequency(speed_mode, timer_num, chan_num, this->channel_, this->bit_depth_, this->frequency_);
246 
247  if (timer_init_result != ESP_OK) {
248  ESP_LOGE(TAG, "Frequency %f can't be achieved with computed bit depth %u", this->frequency_, this->bit_depth_);
249  this->status_set_error();
250  return;
251  }
252 
253  this->status_clear_error();
254 #endif
255  // re-apply duty
256  this->write_state(this->duty_);
257 }
258 
259 uint8_t next_ledc_channel = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
260 
261 } // namespace ledc
262 } // namespace esphome
263 
264 #endif
virtual void turn_off()
Disable this binary output.
Definition: binary_output.h:51
uint8_t next_ledc_channel
void update_frequency(float frequency) override
Dynamically change frequency at runtime.
virtual uint8_t get_pin() const =0
void status_set_error(const char *message="unspecified")
Definition: component.cpp:159
ledc_mode_t get_speed_mode(uint8_t channel)
Definition: ledc_output.cpp:38
void write_state(float state) override
Override FloatOutput&#39;s write_state.
uint16_le_t frequency
Definition: bl0942.h:21
void status_clear_error()
Definition: component.cpp:172
constexpr int ledc_angle_to_htop(float angle, uint8_t bit_depth)
void setup() override
Setup LEDC.
void dump_config() override
float ledc_min_frequency_for_bit_depth(uint8_t bit_depth, bool low_frequency)
Definition: ledc_output.cpp:49
optional< uint8_t > ledc_bit_depth_for_frequency(float frequency)
Definition: ledc_output.cpp:54
InternalGPIOPin * pin_
Definition: ledc_output.h:36
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
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)
Definition: ledc_output.cpp:68
float ledc_max_frequency_for_bit_depth(uint8_t bit_depth)
Definition: ledc_output.cpp:47
virtual bool is_inverted() const =0
bool state
Definition: fan.h:34