ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
led_strip.cpp
Go to the documentation of this file.
1#include "led_strip.h"
2#include <algorithm>
3#include <cinttypes>
4
5#ifdef USE_ESP32
6
8#include "esphome/core/log.h"
9
10#include <esp_attr.h>
11#include <esp_clk_tree.h>
12
14
15ESPHOME_LOG_TAG(TAG, "esp32_rmt_led_strip");
16
17static const size_t RMT_SYMBOLS_PER_BYTE = 8;
18// Idle time the line must stay low between frames so the strip latches
19static constexpr uint32_t RESET_GAP_US = 50;
20
21// Query the RMT default clock source frequency. This varies by variant:
22// APB (80MHz) on ESP32/S2/S3/C3, PLL_F80M (80MHz) on C6/P4, XTAL (32MHz) on H2.
23// Worst-case reset time is WS2811 at 300µs = 24000 ticks at 80MHz, well within
24// the 15-bit rmt_symbol_word_t duration field max of 32767.
25static uint32_t rmt_resolution_hz() {
26 uint32_t freq;
27 esp_clk_tree_src_get_freq_hz((soc_module_clk_t) RMT_CLK_SRC_DEFAULT, ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED, &freq);
28 return freq;
29}
30
31#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
32static size_t IRAM_ATTR HOT encoder_callback(const void *data, size_t size, size_t symbols_written, size_t symbols_free,
33 rmt_symbol_word_t *symbols, bool *done, void *arg) {
34 auto *params = static_cast<LedParams *>(arg);
35 const auto *bytes = static_cast<const uint8_t *>(data);
36 size_t index = symbols_written / RMT_SYMBOLS_PER_BYTE;
37
38 // convert byte to symbols
39 if (index < size) {
40 if (symbols_free < RMT_SYMBOLS_PER_BYTE) {
41 return 0;
42 }
43 for (size_t i = 0; i < RMT_SYMBOLS_PER_BYTE; i++) {
44 if (bytes[index] & (1 << (7 - i))) {
45 symbols[i] = params->bit1;
46 } else {
47 symbols[i] = params->bit0;
48 }
49 }
50#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 1)
51 if ((index + 1) >= size && params->reset.duration0 == 0 && params->reset.duration1 == 0) {
52 *done = true;
53 }
54#endif
55 return RMT_SYMBOLS_PER_BYTE;
56 }
57
58 // send reset
59 if (symbols_free < 1) {
60 return 0;
61 }
62 symbols[0] = params->reset;
63 *done = true;
64 return 1;
65}
66#endif
67
69 size_t buffer_size = this->get_buffer_size_();
70
72 if (!this->internal_accessor_.allocate(allocator, this->num_leds_)) {
73 this->mark_failed(LOG_STR(ESP_LOG_MSG_ALLOC_FAIL));
74 return;
75 }
76
77#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
78 // copy of the led buffer
79 this->rmt_buf_ = allocator.allocate(buffer_size);
80#else
82
83 // 8 bits per byte, 1 rmt_symbol_word_t per bit + 1 rmt_symbol_word_t for reset
84 this->rmt_buf_ = rmt_allocator.allocate(buffer_size * 8 + 1);
85#endif
86
87 const uint32_t resolution_hz = rmt_resolution_hz();
88 // Longest wire time of one frame; write_state() defers instead of blocking until it has elapsed
89 uint32_t bit_ticks = std::max(this->params_.bit0.duration0 + this->params_.bit0.duration1,
90 this->params_.bit1.duration0 + this->params_.bit1.duration1);
91 uint64_t frame_ticks = (uint64_t) bit_ticks * buffer_size * RMT_SYMBOLS_PER_BYTE + this->params_.reset.duration0 +
92 this->params_.reset.duration1;
93 this->frame_time_us_ = frame_ticks * 1000000 / resolution_hz + RESET_GAP_US;
94 // Seed with the interval write_state() gates on, so the first frame is not deferred
95 this->last_refresh_ = micros() - std::max(this->frame_time_us_, this->max_refresh_rate_);
96
97 rmt_tx_channel_config_t channel;
98 memset(&channel, 0, sizeof(channel));
99 channel.clk_src = RMT_CLK_SRC_DEFAULT;
100 channel.resolution_hz = resolution_hz;
101 channel.gpio_num = gpio_num_t(this->pin_);
102 channel.mem_block_symbols = this->rmt_symbols_;
103 channel.trans_queue_depth = 1;
104 channel.flags.invert_out = this->invert_out_;
105 channel.flags.with_dma = this->use_dma_;
106 channel.intr_priority = 0;
107 if (rmt_new_tx_channel(&channel, &this->channel_) != ESP_OK) {
108 this->mark_failed(LOG_STR("Channel creation failed"));
109 return;
110 }
111
112#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
113 rmt_simple_encoder_config_t encoder;
114 memset(&encoder, 0, sizeof(encoder));
115 encoder.callback = encoder_callback;
116 encoder.arg = &this->params_;
117 encoder.min_chunk_size = RMT_SYMBOLS_PER_BYTE;
118 if (rmt_new_simple_encoder(&encoder, &this->encoder_) != ESP_OK) {
119 this->mark_failed(LOG_STR("Encoder creation failed"));
120 return;
121 }
122#else
123 rmt_copy_encoder_config_t encoder;
124 memset(&encoder, 0, sizeof(encoder));
125 if (rmt_new_copy_encoder(&encoder, &this->encoder_) != ESP_OK) {
126 this->mark_failed(LOG_STR("Encoder creation failed"));
127 return;
128 }
129#endif
130
131 if (rmt_enable(this->channel_) != ESP_OK) {
132 this->mark_failed(LOG_STR("Enabling channel failed"));
133 return;
134 }
135
136 this->accessor_ = &this->internal_accessor_;
137}
138
140 uint32_t bit1_low, uint32_t reset_time_high, uint32_t reset_time_low) {
141 float ratio = (float) rmt_resolution_hz() / 1e09f;
142
143 // 0-bit
144 this->params_.bit0.duration0 = (uint32_t) (ratio * bit0_high);
145 this->params_.bit0.level0 = 1;
146 this->params_.bit0.duration1 = (uint32_t) (ratio * bit0_low);
147 this->params_.bit0.level1 = 0;
148 // 1-bit
149 this->params_.bit1.duration0 = (uint32_t) (ratio * bit1_high);
150 this->params_.bit1.level0 = 1;
151 this->params_.bit1.duration1 = (uint32_t) (ratio * bit1_low);
152 this->params_.bit1.level1 = 0;
153 // reset
154 this->params_.reset.duration0 = (uint32_t) (ratio * reset_time_high);
155 this->params_.reset.level0 = 1;
156 this->params_.reset.duration1 = (uint32_t) (ratio * reset_time_low);
157 this->params_.reset.level1 = 0;
158}
159
161 // Previous frame still on the wire, inside its reset gap, or refreshing too often: try again next loop
162 if (this->throttle_show_(micros(), this->last_refresh_, std::max(this->frame_time_us_, this->max_refresh_rate_)))
163 return;
164
165 // The gate above should always cover the previous frame; never overwrite rmt_buf_ while the RMT still reads it
166 if (rmt_tx_wait_all_done(this->channel_, 0) != ESP_OK) {
167 ESP_LOGE(TAG, "RMT TX still busy");
168 this->status_set_warning();
169 this->schedule_show();
170 return;
171 }
172 this->mark_shown_();
173
174 ESP_LOGVV(TAG, "Writing RGB values to bus");
175
176#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
177 memcpy(this->rmt_buf_, this->internal_accessor_.color_data, this->get_buffer_size_());
178#else
179 size_t buffer_size = this->get_buffer_size_();
180
181 size_t size = 0;
182 size_t len = 0;
183 uint8_t *psrc = this->internal_accessor_.color_data;
184 rmt_symbol_word_t *pdest = this->rmt_buf_;
185 while (size < buffer_size) {
186 uint8_t b = *psrc;
187 for (int i = 0; i < 8; i++) {
188 pdest->val = b & (1 << (7 - i)) ? this->params_.bit1.val : this->params_.bit0.val;
189 pdest++;
190 len++;
191 }
192 size++;
193 psrc++;
194 }
195
196 if (this->params_.reset.duration0 > 0 || this->params_.reset.duration1 > 0) {
197 pdest->val = this->params_.reset.val;
198 pdest++;
199 len++;
200 }
201#endif
202
203 rmt_transmit_config_t config;
204 memset(&config, 0, sizeof(config));
205#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
206 esp_err_t error = rmt_transmit(this->channel_, this->encoder_, this->rmt_buf_, this->get_buffer_size_(), &config);
207#else
208 esp_err_t error =
209 rmt_transmit(this->channel_, this->encoder_, this->rmt_buf_, len * sizeof(rmt_symbol_word_t), &config);
210#endif
211 if (!this->status_comm_result(error == ESP_OK, nullptr)) {
212 ESP_LOGE(TAG, "RMT TX error");
213 // retry next loop iteration so the frame is not lost
214 this->schedule_show();
215 return;
216 }
217 // Stamped after the transfer started so the gate above stays conservative
218 this->last_refresh_ = micros();
219}
220
222 ESP_LOGCONFIG(TAG,
223 "ESP32 RMT LED Strip:\n"
224 " Pin: %u",
225 this->pin_);
226 ESP_LOGCONFIG(TAG, " RMT Symbols: %" PRIu32, this->rmt_symbols_);
227 char channel_colors[5];
228 ESP_LOGCONFIG(TAG,
229 " Channel colors: %s\n"
230 " Max refresh rate: %" PRIu32 "\n"
231 " Number of LEDs: %u",
232 this->internal_accessor_.channel_colors.to_string(channel_colors), this->max_refresh_rate_,
233 this->num_leds_);
234}
235
237
238} // namespace esphome::esp32_rmt_led_strip
239
240#endif // USE_ESP32
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
T * allocate(size_t n)
Definition helpers.h:2423
void write_state(light::LightState *state) override
void set_led_params(uint32_t bit0_high, uint32_t bit0_low, uint32_t bit1_high, uint32_t bit1_low, uint32_t reset_time_high, uint32_t reset_time_low)
light::CorrectedBufferColorAccessor internal_accessor_
Definition led_strip.h:64
bool throttle_show_(uint32_t now_us, uint32_t last_us, uint32_t interval_us)
bool allocate(RAMAllocator< uint8_t > &allocator, size_t num_leds, size_t extra_bytes=0)
Allocate the color and effect data for num_leds LEDs as one zeroed block, followed by extra_bytes mor...
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:68
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "esp32_rmt_led_strip")
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:43
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
static void uint32_t
const char * to_string(char *buf) const
Write the order back out as text, e.g.