ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
i2c_bus_esp_idf.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "i2c_bus_esp_idf.h"
4
5#include <driver/gpio.h>
6#include <cinttypes>
7#include <cstring>
9#include "esphome/core/hal.h"
11#include "esphome/core/log.h"
12
13#ifdef USE_I2C_ISR_GUARD
14#include <esp_intr_alloc.h>
15#include <hal/i2c_ll.h> // declares i2c_periph_signal (IDF 5: soc/, IDF 6: hal/)
16#if SOC_I2C_SUPPORT_HW_FSM_RST || I2C_LL_SUPPORT_HW_FSM_RST
17#error "This chip has an I2C FSM reset; the ISR guard is no longer needed"
18#endif
19
20namespace esphome::i2c {
21// Without an FSM reset ACK_ERR can stay raised and the IDF ISR never masks it (esp-idf#17690). Mask the master
22// events until the next transaction when an error is raised both before and after the handler clears it.
23static constexpr uint32_t I2C_ERROR_INTR = I2C_LL_INTR_NACK | I2C_LL_INTR_TIMEOUT | I2C_LL_INTR_ARBITRATION;
24static_assert((I2C_LL_MASTER_EVENT_INTR & I2C_ERROR_INTR) == I2C_ERROR_INTR,
25 "The master event mask must cover the error interrupts");
26
27struct I2CIsrGuard {
28 intr_handler_t handler;
29 void *arg;
30 i2c_dev_t *dev;
31};
32static I2CIsrGuard i2c_isr_guards[SOC_HP_I2C_NUM]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
33
34static void IRAM_ATTR i2c_isr_guard(void *arg) {
35 auto *guard = static_cast<I2CIsrGuard *>(arg);
36 uint32_t before;
37 i2c_ll_get_intr_mask(guard->dev, &before);
38 guard->handler(guard->arg);
39 uint32_t after;
40 i2c_ll_get_intr_mask(guard->dev, &after);
41 if (before & after & I2C_ERROR_INTR)
42 i2c_ll_disable_intr_mask(guard->dev, I2C_LL_MASTER_EVENT_INTR);
43}
44
45static int i2c_port_for_source(int source) {
46 for (int port = 0; port < SOC_HP_I2C_NUM; port++) {
47 if (source == i2c_periph_signal[port].irq)
48 return port;
49 }
50 return -1;
51}
52} // namespace esphome::i2c
53
54// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
55extern "C" {
56esp_err_t __real_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler,
57 void *arg, intr_handle_t *ret_handle);
58
59esp_err_t __wrap_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler,
60 void *arg, intr_handle_t *ret_handle) {
61 int port = esphome::i2c::i2c_port_for_source(source);
62 if (port < 0)
63 return __real_esp_intr_alloc_intrstatus(source, flags, reg, mask, handler, arg, ret_handle);
64 auto &guard = esphome::i2c::i2c_isr_guards[port];
65 auto previous = guard;
66 guard = {handler, arg, I2C_LL_GET_HW(port)};
67 esp_err_t err =
68 __real_esp_intr_alloc_intrstatus(source, flags, reg, mask, esphome::i2c::i2c_isr_guard, &guard, ret_handle);
69 if (err != ESP_OK)
70 guard = previous; // a failed allocation leaves the live guard alone
71 return err;
72}
73} // extern "C"
74// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
75#endif // USE_I2C_ISR_GUARD
76
77namespace esphome::i2c {
78
79ESPHOME_LOG_TAG(TAG, "i2c");
80
81// Maximum bytes to log in hex format (truncates larger transfers)
82static constexpr size_t I2C_MAX_LOG_BYTES = 32;
83
85 static i2c_port_t next_hp_port = I2C_NUM_0;
86#if SOC_LP_I2C_SUPPORTED
87 static i2c_port_t next_lp_port = LP_I2C_NUM_0;
88#endif
89
90 if (this->timeout_ > 13000) {
91 ESP_LOGW(TAG, "Using max allowed timeout: 13 ms");
92 this->timeout_ = 13000;
93 }
94
95 this->recover_();
96
97 i2c_master_bus_config_t bus_conf{};
98 memset(&bus_conf, 0, sizeof(bus_conf));
99 bus_conf.sda_io_num = gpio_num_t(this->sda_pin_);
100 bus_conf.scl_io_num = gpio_num_t(this->scl_pin_);
101 bus_conf.glitch_ignore_cnt = 7;
102#if SOC_LP_I2C_SUPPORTED
103 if (this->lp_mode_) {
104 if ((next_lp_port - LP_I2C_NUM_0) == SOC_LP_I2C_NUM) {
105 ESP_LOGE(TAG, "No more than %u LP buses supported", SOC_LP_I2C_NUM);
106 this->mark_failed();
107 return;
108 }
109 this->port_ = next_lp_port;
110 next_lp_port = (i2c_port_t) (next_lp_port + 1);
111 bus_conf.lp_source_clk = LP_I2C_SCLK_DEFAULT;
112 } else {
113#endif
114 if (next_hp_port == SOC_HP_I2C_NUM) {
115 ESP_LOGE(TAG, "No more than %u HP buses supported", SOC_HP_I2C_NUM);
116 this->mark_failed();
117 return;
118 }
119 this->port_ = next_hp_port;
120 next_hp_port = (i2c_port_t) (next_hp_port + 1);
121 bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
122#if SOC_LP_I2C_SUPPORTED
123 }
124#endif
125 bus_conf.i2c_port = this->port_;
126 bus_conf.flags.enable_internal_pullup = this->sda_pullup_enabled_ || this->scl_pullup_enabled_;
127 esp_err_t err = i2c_new_master_bus(&bus_conf, &this->bus_);
128 if (err != ESP_OK) {
129 ESP_LOGW(TAG, "i2c_new_master_bus failed: %s", esp_err_to_name(err));
130 this->mark_failed();
131 return;
132 }
133
134 this->dev_ = this->add_device_(this->frequency_);
135 if (this->dev_ == nullptr) {
136 this->mark_failed();
137 return;
138 }
139#ifdef I2C_PORT_FREQUENCY_COUNT
140 this->add_frequency(this->frequency_);
141 for (auto &device : this->devices_) {
142 device.dev = device.frequency == this->frequency_ ? this->dev_ : this->add_device_(device.frequency);
143 if (device.dev == nullptr) {
144 this->mark_failed();
145 return;
146 }
147 }
148#endif
149
150 this->initialized_ = true;
151
152 if (this->scan_) {
153 ESP_LOGV(TAG, "Scanning for devices");
154 this->i2c_scan_();
155 }
156}
157
158i2c_master_dev_handle_t IDFI2CBus::add_device_(uint32_t frequency) {
159 i2c_device_config_t dev_conf{};
160 dev_conf.dev_addr_length = I2C_ADDR_BIT_LEN_7;
161 dev_conf.device_address = I2C_DEVICE_ADDRESS_NOT_USED;
162 dev_conf.scl_speed_hz = frequency;
163 dev_conf.scl_wait_us = this->timeout_;
164 i2c_master_dev_handle_t dev{};
165 const esp_err_t err = i2c_master_bus_add_device(this->bus_, &dev_conf, &dev);
166 if (err != ESP_OK) {
167 ESP_LOGW(TAG, "i2c_master_bus_add_device failed: %s", esp_err_to_name(err));
168 return nullptr;
169 }
170 return dev;
171}
172
174 ESP_LOGCONFIG(TAG, "I2C Bus:");
175 ESP_LOGCONFIG(TAG,
176 " SDA Pin: GPIO%u\n"
177 " SCL Pin: GPIO%u\n"
178 " Frequency: %" PRIu32 " Hz",
179 this->sda_pin_, this->scl_pin_, this->frequency_);
180 if (this->timeout_ > 0) {
181 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 "us", this->timeout_);
182 }
183#ifdef USE_I2C_ISR_GUARD
184 // Null when the IDF driver no longer allocates its interrupt through the wrapped call
185 if (i2c_isr_guards[this->port_].handler == nullptr) {
186 ESP_LOGW(TAG, " Interrupt guard inactive");
187 }
188#endif
189 switch (this->recovery_result_) {
191 ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
192 break;
194 ESP_LOGCONFIG(TAG, " Recovery: failed, SCL is held low on the bus");
195 break;
197 ESP_LOGCONFIG(TAG, " Recovery: failed, SDA is held low on the bus");
198 break;
199 }
200 this->dump_scan_results_();
201}
202
203ErrorCode IDFI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
204 size_t read_count) {
205 // logging is only enabled with v level, if warnings are shown the caller
206 // should log them
207 if (!this->initialized_) {
208 ESP_LOGW(TAG, "i2c bus not initialized!");
210 }
211
212 i2c_operation_job_t jobs[8]{};
213 size_t num_jobs = 0;
214 uint8_t write_addr = (address << 1) | I2C_MASTER_WRITE;
215 uint8_t read_addr = (address << 1) | I2C_MASTER_READ;
216 ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", write_count, read_count);
217 if (read_count == 0 && write_count == 0) {
218 // basically just a bus probe. Send a start, address and stop
219 ESP_LOGV(TAG, "0x%02X BUS PROBE", address);
220 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
221 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
222 jobs[num_jobs].write.ack_check = true;
223 jobs[num_jobs].write.data = &write_addr;
224 jobs[num_jobs++].write.total_bytes = 1;
225 } else {
226 if (write_count != 0) {
227 ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
228 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
229 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
230 jobs[num_jobs].write.ack_check = true;
231 jobs[num_jobs].write.data = &write_addr;
232 jobs[num_jobs++].write.total_bytes = 1;
233 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
234 jobs[num_jobs].write.ack_check = true;
235 jobs[num_jobs].write.data = (uint8_t *) write_buffer;
236 jobs[num_jobs++].write.total_bytes = write_count;
237 }
238 if (read_count != 0) {
239 ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
240 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
241 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
242 jobs[num_jobs].write.ack_check = true;
243 jobs[num_jobs].write.data = &read_addr;
244 jobs[num_jobs++].write.total_bytes = 1;
245 if (read_count > 1) {
246 jobs[num_jobs].command = I2C_MASTER_CMD_READ;
247 jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
248 jobs[num_jobs].read.data = read_buffer;
249 jobs[num_jobs++].read.total_bytes = read_count - 1;
250 }
251 jobs[num_jobs].command = I2C_MASTER_CMD_READ;
252 jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
253 jobs[num_jobs].read.data = read_buffer + read_count - 1;
254 jobs[num_jobs++].read.total_bytes = 1;
255 }
256 }
257 jobs[num_jobs++].command = I2C_MASTER_CMD_STOP;
258 ESP_LOGV(TAG, "Sending %zu jobs", num_jobs);
259 esp_err_t err = i2c_master_execute_defined_operations(this->dev_, jobs, num_jobs, 100);
260 if (err == ESP_ERR_INVALID_STATE || err == ESP_ERR_INVALID_RESPONSE) {
261 ESP_LOGV(TAG, "TX to %02X failed: not acked", address);
263 } else if (err == ESP_ERR_TIMEOUT) {
264 ESP_LOGV(TAG, "TX to %02X failed: timeout", address);
265 return ERROR_TIMEOUT;
266 } else if (err != ESP_OK) {
267 ESP_LOGV(TAG, "TX to %02X failed: %s", address, esp_err_to_name(err));
268 return ERROR_UNKNOWN;
269 }
270 return ERROR_OK;
271}
272
273#ifdef I2C_PORT_FREQUENCY_COUNT
275 for (const auto &device : this->devices_) {
276 if (device.frequency == frequency) {
277 return;
278 }
279 }
280 this->devices_.push_back({frequency, nullptr});
281}
282
284 if (this->frequency_ == frequency) {
285 return ERROR_OK;
286 }
287 if (!this->initialized_) {
288 this->frequency_ = frequency;
289 return ERROR_OK;
290 }
291 // Every handle exists since setup(); a frequency nobody registered has none
292 for (const auto &device : this->devices_) {
293 if (device.frequency == frequency) {
294 this->dev_ = device.dev;
295 this->frequency_ = frequency;
296 return ERROR_OK;
297 }
298 }
299 return ERROR_UNKNOWN;
300}
301#endif
302
306void IDFI2CBus::recover_() {
307 ESP_LOGI(TAG, "Performing bus recovery");
308
309 const auto scl_pin = static_cast<gpio_num_t>(this->scl_pin_);
310 const auto sda_pin = static_cast<gpio_num_t>(this->sda_pin_);
311
312 // For the upcoming operations, target for a 60kHz toggle frequency.
313 // 1000kHz is the maximum frequency for I2C running in standard-mode,
314 // but lower frequencies are not a problem.
315 // Note: the timing that is used here is chosen manually, to get
316 // results that are close to the timing that can be archieved by the
317 // implementation for the Arduino framework.
318 const auto half_period_usec = 7;
319
320 // Configure SCL pin for open drain input/output, with a pull up resistor.
321 gpio_set_level(scl_pin, 1);
322 gpio_config_t scl_config{};
323 scl_config.pin_bit_mask = 1ULL << this->scl_pin_;
324 scl_config.mode = GPIO_MODE_INPUT_OUTPUT_OD;
325 scl_config.pull_up_en = GPIO_PULLUP_ENABLE;
326 scl_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
327 scl_config.intr_type = GPIO_INTR_DISABLE;
328 gpio_config(&scl_config);
329
330 // Configure SDA pin for open drain input/output, with a pull up resistor.
331 gpio_set_level(sda_pin, 1);
332 gpio_config_t sda_conf{};
333 sda_conf.pin_bit_mask = 1ULL << this->sda_pin_;
334 sda_conf.mode = GPIO_MODE_INPUT_OUTPUT_OD;
335 sda_conf.pull_up_en = GPIO_PULLUP_ENABLE;
336 sda_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
337 sda_conf.intr_type = GPIO_INTR_DISABLE;
338 gpio_config(&sda_conf);
339
340 // If SCL is pulled low on the I2C bus, then some device is interfering
341 // with the SCL line. In that case, the I2C bus cannot be recovered.
342 delayMicroseconds(half_period_usec);
343 if (gpio_get_level(scl_pin) == 0) {
344 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW on the bus");
345 this->recovery_result_ = RECOVERY_FAILED_SCL_LOW;
346 return;
347 }
348
349 // From the specification:
350 // "If the data line (SDA) is stuck LOW, send nine clock pulses. The
351 // device that held the bus LOW should release it sometime within
352 // those nine clocks."
353 // We don't really have to detect if SDA is stuck low. We'll simply send
354 // nine clock pulses here, just in case SDA is stuck. Actual checks on
355 // the SDA line status will be done after the clock pulses.
356 for (auto i = 0; i < 9; i++) {
357 gpio_set_level(scl_pin, 0);
358 delayMicroseconds(half_period_usec);
359 gpio_set_level(scl_pin, 1);
360 delayMicroseconds(half_period_usec);
361
362 // When SCL is kept LOW at this point, we might be looking at a device
363 // that applies clock stretching. Wait for the release of the SCL line,
364 // but not forever. There is no specification for the maximum allowed
365 // time. We yield and reset the WDT, so as to avoid triggering reset.
366 // No point in trying to recover the bus by forcing a uC reset. Bus
367 // should recover in a few ms or less else not likely to recovery at
368 // all.
369 auto wait = 250;
370 while (wait-- && gpio_get_level(scl_pin) == 0) {
371 App.feed_wdt();
372 delayMicroseconds(half_period_usec * 2);
373 }
374 if (gpio_get_level(scl_pin) == 0) {
375 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW during clock pulse cycle");
376 this->recovery_result_ = RECOVERY_FAILED_SCL_LOW;
377 return;
378 }
379 }
380
381 // By now, any stuck device ought to have sent all remaining bits of its
382 // transaction, meaning that it should have freed up the SDA line, resulting
383 // in SDA being pulled up.
384 if (gpio_get_level(sda_pin) == 0) {
385 ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
386 this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
387 return;
388 }
389
390 // From the specification:
391 // "I2C-bus compatible devices must reset their bus logic on receipt of
392 // a START or repeated START condition such that they all anticipate
393 // the sending of a target address, even if these START conditions are
394 // not positioned according to the proper format."
395 // While the 9 clock pulses from above might have drained all bits of a
396 // single byte within a transaction, a device might have more bytes to
397 // transmit. So here we'll generate a START condition to snap the device
398 // out of this state.
399 // SCL and SDA are already high at this point, so we can generate a START
400 // condition by making the SDA signal LOW.
401 delayMicroseconds(half_period_usec);
402 gpio_set_level(sda_pin, 0);
403
404 // From the specification:
405 // "A START condition immediately followed by a STOP condition (void
406 // message) is an illegal format. Many devices however are designed to
407 // operate properly under this condition."
408 // Finally, we'll bring the I2C bus into a starting state by generating
409 // a STOP condition.
410 delayMicroseconds(half_period_usec);
411 gpio_set_level(sda_pin, 1);
412
413 this->recovery_result_ = RECOVERY_COMPLETED;
414}
415
416} // namespace esphome::i2c
417#endif // USE_ESP32
uint16_le_t frequency
Definition bl0942.h:6
void feed_wdt()
Feed the task watchdog.
void mark_failed()
Mark this component as failed.
bool scan_
Should we scan ? Can be set in the yaml.
Definition i2c_bus.h:73
void dump_scan_results_()
Logs the scan results at config level, if the bus was scanned.
Definition i2c.cpp:24
void i2c_scan_()
Scans the I2C bus for devices.
Definition i2c.cpp:11
ErrorCode switch_frequency(uint32_t frequency) override
StaticVector< FrequencyDevice, I2C_PORT_FREQUENCY_COUNT+1 > devices_
i2c_master_bus_handle_t bus_
void add_frequency(uint32_t frequency)
Register a frequency used on the bus so setup() creates its device handle.
i2c_master_dev_handle_t dev_
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer, size_t read_count) override
uint16_t flags
esp_err_t __wrap_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle)
esp_err_t __real_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle)
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:13
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
@ ERROR_TIMEOUT
timeout while waiting to receive bytes
Definition i2c_bus.h:18
@ ERROR_NOT_ACKNOWLEDGED
I2C bus acknowledgment not received.
Definition i2c_bus.h:17
@ ERROR_NOT_INITIALIZED
call method to a not initialized bus
Definition i2c_bus.h:19
@ ERROR_UNKNOWN
miscellaneous I2C error during execution
Definition i2c_bus.h:21
ESPHOME_LOG_TAG(TAG, "i2c")
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t