ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
i2s_clockless_led_strip.cpp
Go to the documentation of this file.
2
3#if defined(USE_ESP32) && SOC_I2S_SUPPORTS_TDM
4
5#include <algorithm>
6#include <cinttypes>
7
9
10#include <driver/i2s_tdm.h>
11#include <esp_attr.h>
12
14
15ESPHOME_LOG_TAG(TAG, "i2s_clockless_led_strip");
16
17constexpr const char *const ERROR_I2S = "I2S error";
18
19// These values are hardcoded for an LED strip at 800 kbps.
20//
21// Each bit of LED strip data gets expanded into 3 bits of I2S data, where a 0-bit expands into 100
22// (1/3 duty cycle) and a 1-bit expands into 110 (2/3 duty cycle. Each byte of LED strip data becomes
23// one 24-bit I2S sample to be transmitted at a rate of 100000 samples per second in I2S TDM mode.
24constexpr uint32_t I2S_SAMPLE_RATE_HZ = 100000;
25constexpr size_t I2S_BYTES_PER_SAMPLE = 3;
26
27// Determine how many I2S samples are needed to feed the output for the specified duration and vice-versa.
28constexpr size_t num_i2s_samples_from_duration_us(uint32_t duration_us) {
29 return (duration_us * I2S_SAMPLE_RATE_HZ + 999999) / 1000000;
30}
31constexpr uint32_t num_i2s_samples_to_duration_us(size_t samples) { return samples * 1000000ull / I2S_SAMPLE_RATE_HZ; }
32
33// Determine the number of I2S samples to pad with zeros after the LED data to encode the LED strip reset signal.
34// Minimum 50 us for WS2811, 80 us for SK6812, 280 us for WS2812B-V5.
38
39// Determine the number of I2S samples per DMA buffer to ensure that the interrupt-driven I2S on_sent callback
40// doesn't run too frequently. For example, if the buffers were sized to hold just 1 RGBW pixel then they would be
41// recycled approximately every 40 us (25000 Hz) which is way too fast. The buffer duration also imposes an upper
42// bound on the maximum LED strip refresh rate. Round up to a multiple of 3 for `dma_frame_num` as required by
43// the ESP-IDF programming guide when using 24-bit samples.
47
48I2SClocklessLedStrip::I2SClocklessLedStrip(uint8_t pin, uint16_t num_leds, light::ChannelColors channel_colors)
49 : internal_accessor_{nullptr, nullptr, channel_colors, &this->correction_},
50 color_data_bytes_(num_leds * channel_colors.bytes_per_led()),
51 num_leds_(num_leds),
52 pin_(pin) {}
53
55 ESP_LOGCONFIG(TAG,
56 "I2S Clockless LED Strip:\n"
57 " Pin: %u",
58 this->pin_);
59 char channel_colors[5];
60 ESP_LOGCONFIG(TAG,
61 " Channel colors: %s\n"
62 " Number of LEDs: %" PRIu16 "\n"
63 " DMA buffer: %" PRIuPTR " samples (%" PRIu32 " us)",
64 this->internal_accessor_.channel_colors.to_string(channel_colors), this->num_leds_, I2S_BUFFER_SAMPLES,
66}
67
69
71 if (!this->allocate_buffers_()) {
72 this->mark_failed(LOG_STR(ESP_LOG_MSG_ALLOC_FAIL));
73 return;
74 }
75
76 i2s_chan_config_t chan_config = {
77 .id = I2S_NUM_AUTO,
78 .role = I2S_ROLE_MASTER,
79 .dma_desc_num = 2,
80 .dma_frame_num = I2S_BUFFER_SAMPLES,
81 .auto_clear_after_cb = false,
82 .auto_clear_before_cb = false,
83 .allow_pd = false,
84 .intr_priority = 0,
85 };
86 esp_err_t err = i2s_new_channel(&chan_config, &this->tx_handle_, NULL);
87 if (err != ESP_OK) {
88 ESP_LOGE(TAG, "Error in i2s_new_channel: %s", esp_err_to_name(err));
89 } else {
90 i2s_tdm_config_t tdm_config = {
91 .clk_cfg =
92 {
93 .sample_rate_hz = I2S_SAMPLE_RATE_HZ,
94 .clk_src = I2S_CLK_SRC_DEFAULT,
95 .mclk_multiple = I2S_MCLK_MULTIPLE_384,
96 },
97 .slot_cfg =
98 {
99 .data_bit_width = I2S_DATA_BIT_WIDTH_24BIT,
100 .slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO,
101 .slot_mode = I2S_SLOT_MODE_MONO,
102 .slot_mask = I2S_TDM_SLOT0,
103 .ws_width = 1,
104 .big_endian = true,
105 .total_slot = I2S_TDM_AUTO_SLOT_NUM,
106 },
107 .gpio_cfg =
108 {
109 .mclk = I2S_GPIO_UNUSED,
110 .bclk = I2S_GPIO_UNUSED,
111 .ws = I2S_GPIO_UNUSED,
112 .dout = gpio_num_t(this->pin_),
113 .din = I2S_GPIO_UNUSED,
114 .invert_flags =
115 {
116 .mclk_inv = false,
117 .bclk_inv = false,
118 .ws_inv = false,
119 },
120 },
121 };
122 err = i2s_channel_init_tdm_mode(this->tx_handle_, &tdm_config);
123 if (err != ESP_OK) {
124 ESP_LOGE(TAG, "Error in i2s_channel_init_tdm_mode: %s", esp_err_to_name(err));
125 } else {
126 i2s_event_callbacks_t event_callbacks = {
127 .on_sent = i2s_on_sent_callback,
128 };
129 err = i2s_channel_register_event_callback(this->tx_handle_, &event_callbacks, this);
130 if (err != ESP_OK) {
131 ESP_LOGE(TAG, "Error in i2s_channel_register_event_callback: %s", esp_err_to_name(err));
132 } else {
133 err = i2s_channel_enable(this->tx_handle_);
134 if (err == ESP_OK) {
135 this->accessor_ = &this->internal_accessor_;
136 return; // Success!
137 }
138 ESP_LOGE(TAG, "Error in i2s_channel_enable: %s", esp_err_to_name(err));
139 }
140 }
141 i2s_del_channel(this->tx_handle_);
142 this->tx_handle_ = {};
143 }
144 this->mark_failed(LOG_STR(ERROR_I2S));
145}
146
148 const size_t i2s_data_bytes = this->color_data_bytes_ * I2S_BYTES_PER_SAMPLE;
149
151 this->i2s_data_ = allocator.allocate(i2s_data_bytes);
152 if (this->i2s_data_ != nullptr) {
153 if (this->internal_accessor_.allocate(allocator, this->num_leds_)) {
154 memset(this->i2s_data_, 0, i2s_data_bytes);
155 return true;
156 }
157 allocator.deallocate(this->i2s_data_, i2s_data_bytes);
158 this->i2s_data_ = nullptr;
159 }
160 return false;
161}
162
164 if (this->is_failed())
165 return;
166
167 if (this->i2s_data_ready_.load(std::memory_order_acquire)) {
168 // Busy sending the last frame, try again later.
169 this->schedule_show();
170 return;
171 }
172
173 const size_t color_data_bytes = this->color_data_bytes_;
174 uint8_t *color_data = this->internal_accessor_.color_data;
175 uint8_t *i2s_data = this->i2s_data_;
176 for (size_t i = 0; i < color_data_bytes; i++) {
177 const uint8_t color_byte = *(color_data++);
178 *(i2s_data++) = 0b10010010 | ((color_byte & 0x80) >> 1) | ((color_byte & 0x40) >> 3) | ((color_byte & 0x20) >> 5);
179 *(i2s_data++) = 0b01001001 | ((color_byte & 0x10) << 1) | ((color_byte & 0x08) >> 1);
180 *(i2s_data++) = 0b00100100 | ((color_byte & 0x04) << 5) | ((color_byte & 0x02) << 3) | ((color_byte & 0x01) << 1);
181 }
182
183 this->i2s_data_sent_ = 0;
184 this->i2s_data_ready_.store(true, std::memory_order_release);
185
186 this->mark_shown_();
187}
188
189bool IRAM_ATTR HOT I2SClocklessLedStrip::i2s_on_sent_callback(i2s_chan_handle_t handle, i2s_event_data_t *event,
190 void *user_ctx) {
191 auto *const self = static_cast<I2SClocklessLedStrip *>(user_ctx);
192 auto *const dma_buf = static_cast<uint8_t *>(event->dma_buf);
193 const size_t dma_buf_size = event->size;
194
195 bool dma_buf_filled = false;
196 if (self->i2s_data_ready_.load(std::memory_order_acquire)) {
197 const size_t i2s_data_bytes = self->color_data_bytes_ * I2S_BYTES_PER_SAMPLE;
198 if (self->i2s_data_sent_ < i2s_data_bytes) {
199 const size_t i2s_data_remaining = i2s_data_bytes - self->i2s_data_sent_;
200 if (i2s_data_remaining >= dma_buf_size) {
201 memcpy(dma_buf, self->i2s_data_ + self->i2s_data_sent_, dma_buf_size);
202 } else {
203 memcpy(dma_buf, self->i2s_data_ + self->i2s_data_sent_, i2s_data_remaining);
204 memset(dma_buf + i2s_data_remaining, 0, dma_buf_size - i2s_data_remaining);
205 }
206 dma_buf_filled = true;
207 }
208 self->i2s_data_sent_ += dma_buf_size;
209 if (self->i2s_data_sent_ >= i2s_data_bytes + I2S_RESET_BYTES) {
210 self->i2s_data_ready_.store(false, std::memory_order_release);
211 }
212 }
213 // We only need to clear the buffer when the first byte is non-zero. Zero is not a value
214 // that can appear within the I2S data that gets copied into the front of the buffer so
215 // if the first byte is zero then the buffer must have already been cleared.
216 if (!dma_buf_filled && dma_buf[0] != 0) {
217 memset(dma_buf, 0, dma_buf_size);
218 }
219 return false;
220}
221
222} // namespace esphome::i2s_clockless_led_strip
223
224#endif
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
void deallocate(T *p, size_t n)
Definition helpers.h:2453
T * allocate(size_t n)
Definition helpers.h:2423
I2SClocklessLedStrip(uint8_t pin, uint16_t num_leds, light::ChannelColors channel_colors)
static bool i2s_on_sent_callback(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
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, "i2s_clockless_led_strip")
constexpr uint32_t num_i2s_samples_to_duration_us(size_t samples)
constexpr size_t num_i2s_samples_from_duration_us(uint32_t duration_us)
constexpr float IO
For components that represent GPIO pins like PCF8573.
Definition component.h:41
static void uint32_t
Which byte of an addressable LED's data carries each colour.
const char * to_string(char *buf) const
Write the order back out as text, e.g.
spi_device_handle_t handle