ESPHome 2026.12.0-dev
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;
25
26// Determine how many I2S samples are needed to feed the output for the specified duration and vice-versa.
27constexpr size_t num_i2s_samples_from_duration_us(uint32_t duration_us) {
28 return (duration_us * I2S_SAMPLE_RATE_HZ + 999999) / 1000000;
29}
30constexpr uint32_t num_i2s_samples_to_duration_us(size_t samples) { return samples * 1000000ull / I2S_SAMPLE_RATE_HZ; }
31
32// Determine the number of I2S samples to pad with zeros after the LED data to encode the LED strip reset signal.
33// Minimum 50 us for WS2811, 80 us for SK6812, 280 us for WS2812B-V5.
36constexpr size_t I2S_RESET_BYTES = I2S_RESET_SAMPLES * I2S_BYTES_PER_SAMPLE;
37
38// Determine the number of I2S samples per DMA buffer to ensure that the interrupt-driven I2S on_sent callback
39// doesn't run too frequently. For example, if the buffers were sized to hold just 1 RGBW pixel then they would be
40// recycled approximately every 40 us (25000 Hz) which is way too fast. The buffer duration also imposes an upper
41// bound on the maximum LED strip refresh rate. Round up to a multiple of 3 for `dma_frame_num` as required by
42// the ESP-IDF programming guide when using 24-bit samples.
46
47I2SClocklessLedStrip::I2SClocklessLedStrip(uint8_t *buffer, uint8_t pin, uint16_t num_leds,
48 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 this->internal_accessor_.set_buffer(buffer, num_leds);
54 this->i2s_data_ = buffer + i2s_data_offset(num_leds, channel_colors.bytes_per_led());
55}
56
58 ESP_LOGCONFIG(TAG,
59 "I2S Clockless LED Strip:\n"
60 " Pin: %u",
61 this->pin_);
62 char channel_colors[5];
63 ESP_LOGCONFIG(TAG,
64 " Channel colors: %s\n"
65 " Number of LEDs: %" PRIu16 "\n"
66 " DMA buffer: %" PRIuPTR " samples (%" PRIu32 " us)",
67 this->internal_accessor_.channel_colors.to_string(channel_colors), this->num_leds_, I2S_BUFFER_SAMPLES,
69}
70
72
74 i2s_chan_config_t chan_config = {
75 .id = I2S_NUM_AUTO,
76 .role = I2S_ROLE_MASTER,
77 .dma_desc_num = 2,
78 .dma_frame_num = I2S_BUFFER_SAMPLES,
79 .auto_clear_after_cb = false,
80 .auto_clear_before_cb = false,
81 .allow_pd = false,
82 .intr_priority = 0,
83 };
84 esp_err_t err = i2s_new_channel(&chan_config, &this->tx_handle_, NULL);
85 if (err != ESP_OK) {
86 ESP_LOGE(TAG, "Error in i2s_new_channel: %s", esp_err_to_name(err));
87 } else {
88 i2s_tdm_config_t tdm_config = {
89 .clk_cfg =
90 {
91 .sample_rate_hz = I2S_SAMPLE_RATE_HZ,
92 .clk_src = I2S_CLK_SRC_DEFAULT,
93 .mclk_multiple = I2S_MCLK_MULTIPLE_384,
94 },
95 .slot_cfg =
96 {
97 .data_bit_width = I2S_DATA_BIT_WIDTH_24BIT,
98 .slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO,
99 .slot_mode = I2S_SLOT_MODE_MONO,
100 .slot_mask = I2S_TDM_SLOT0,
101 .ws_width = 1,
102 .big_endian = true,
103 .total_slot = I2S_TDM_AUTO_SLOT_NUM,
104 },
105 .gpio_cfg =
106 {
107 .mclk = I2S_GPIO_UNUSED,
108 .bclk = I2S_GPIO_UNUSED,
109 .ws = I2S_GPIO_UNUSED,
110 .dout = gpio_num_t(this->pin_),
111 .din = I2S_GPIO_UNUSED,
112 .invert_flags =
113 {
114 .mclk_inv = false,
115 .bclk_inv = false,
116 .ws_inv = false,
117 },
118 },
119 };
120 err = i2s_channel_init_tdm_mode(this->tx_handle_, &tdm_config);
121 if (err != ESP_OK) {
122 ESP_LOGE(TAG, "Error in i2s_channel_init_tdm_mode: %s", esp_err_to_name(err));
123 } else {
124 i2s_event_callbacks_t event_callbacks = {
125 .on_sent = i2s_on_sent_callback,
126 };
127 err = i2s_channel_register_event_callback(this->tx_handle_, &event_callbacks, this);
128 if (err != ESP_OK) {
129 ESP_LOGE(TAG, "Error in i2s_channel_register_event_callback: %s", esp_err_to_name(err));
130 } else {
131 err = i2s_channel_enable(this->tx_handle_);
132 if (err == ESP_OK) {
133 this->accessor_ = &this->internal_accessor_;
134 return; // Success!
135 }
136 ESP_LOGE(TAG, "Error in i2s_channel_enable: %s", esp_err_to_name(err));
137 }
138 }
139 i2s_del_channel(this->tx_handle_);
140 this->tx_handle_ = {};
141 }
142 this->mark_failed(LOG_STR(ERROR_I2S));
143}
144
146 if (this->is_failed())
147 return;
148
149 if (this->i2s_data_ready_.load(std::memory_order_acquire)) {
150 // Busy sending the last frame, try again later.
151 this->schedule_show();
152 return;
153 }
154
155 const size_t color_data_bytes = this->color_data_bytes_;
156 uint8_t *color_data = this->internal_accessor_.color_data;
157 uint8_t *i2s_data = this->i2s_data_;
158 for (size_t i = 0; i < color_data_bytes; i++) {
159 const uint8_t color_byte = *(color_data++);
160 *(i2s_data++) = 0b10010010 | ((color_byte & 0x80) >> 1) | ((color_byte & 0x40) >> 3) | ((color_byte & 0x20) >> 5);
161 *(i2s_data++) = 0b01001001 | ((color_byte & 0x10) << 1) | ((color_byte & 0x08) >> 1);
162 *(i2s_data++) = 0b00100100 | ((color_byte & 0x04) << 5) | ((color_byte & 0x02) << 3) | ((color_byte & 0x01) << 1);
163 }
164
165 this->i2s_data_sent_ = 0;
166 this->i2s_data_ready_.store(true, std::memory_order_release);
167
168 this->mark_shown_();
169}
170
171bool IRAM_ATTR HOT I2SClocklessLedStrip::i2s_on_sent_callback(i2s_chan_handle_t handle, i2s_event_data_t *event,
172 void *user_ctx) {
173 auto *const self = static_cast<I2SClocklessLedStrip *>(user_ctx);
174 auto *const dma_buf = static_cast<uint8_t *>(event->dma_buf);
175 const size_t dma_buf_size = event->size;
176
177 bool dma_buf_filled = false;
178 if (self->i2s_data_ready_.load(std::memory_order_acquire)) {
179 const size_t i2s_data_bytes = self->color_data_bytes_ * I2S_BYTES_PER_SAMPLE;
180 if (self->i2s_data_sent_ < i2s_data_bytes) {
181 const size_t i2s_data_remaining = i2s_data_bytes - self->i2s_data_sent_;
182 if (i2s_data_remaining >= dma_buf_size) {
183 memcpy(dma_buf, self->i2s_data_ + self->i2s_data_sent_, dma_buf_size);
184 } else {
185 memcpy(dma_buf, self->i2s_data_ + self->i2s_data_sent_, i2s_data_remaining);
186 memset(dma_buf + i2s_data_remaining, 0, dma_buf_size - i2s_data_remaining);
187 }
188 dma_buf_filled = true;
189 }
190 self->i2s_data_sent_ += dma_buf_size;
191 if (self->i2s_data_sent_ >= i2s_data_bytes + I2S_RESET_BYTES) {
192 self->i2s_data_ready_.store(false, std::memory_order_release);
193 }
194 }
195 // We only need to clear the buffer when the first byte is non-zero. Zero is not a value
196 // that can appear within the I2S data that gets copied into the front of the buffer so
197 // if the first byte is zero then the buffer must have already been cleared.
198 if (!dma_buf_filled && dma_buf[0] != 0) {
199 memset(dma_buf, 0, dma_buf_size);
200 }
201 return false;
202}
203
204} // namespace esphome::i2s_clockless_led_strip
205
206#endif
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
I2SClocklessLedStrip(uint8_t *buffer, uint8_t pin, uint16_t num_leds, light::ChannelColors channel_colors)
buffer is a word aligned block of buffer_bytes().
static bool i2s_on_sent_callback(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
uint8_t * set_buffer(uint8_t *buffer, size_t num_leds)
Use buffer for the color data of num_leds LEDs followed by their effect data, buffer_bytes() in all.
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:74
bool state
Definition fan.h:2
uint32_t buffer
Definition gif.cpp:50
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:42
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