ESPHome 2025.6.3
Loading...
Searching...
No Matches
i2c_bus_esp_idf.cpp
Go to the documentation of this file.
1#ifdef USE_ESP_IDF
2
3#include "i2c_bus_esp_idf.h"
4#include <cinttypes>
5#include <cstring>
7#include "esphome/core/hal.h"
9#include "esphome/core/log.h"
10
11#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 3, 0)
12#define SOC_HP_I2C_NUM SOC_I2C_NUM
13#endif
14
15namespace esphome {
16namespace i2c {
17
18static const char *const TAG = "i2c.idf";
19
21 ESP_LOGCONFIG(TAG, "Running setup");
22 static i2c_port_t next_port = I2C_NUM_0;
23 port_ = next_port;
24#if SOC_HP_I2C_NUM > 1
25 next_port = (next_port == I2C_NUM_0) ? I2C_NUM_1 : I2C_NUM_MAX;
26#else
27 next_port = I2C_NUM_MAX;
28#endif
29
30 if (port_ == I2C_NUM_MAX) {
31 ESP_LOGE(TAG, "No more than %u buses supported", SOC_HP_I2C_NUM);
32 this->mark_failed();
33 return;
34 }
35
36 recover_();
37
38 i2c_config_t conf{};
39 memset(&conf, 0, sizeof(conf));
40 conf.mode = I2C_MODE_MASTER;
41 conf.sda_io_num = sda_pin_;
42 conf.sda_pullup_en = sda_pullup_enabled_;
43 conf.scl_io_num = scl_pin_;
44 conf.scl_pullup_en = scl_pullup_enabled_;
45 conf.master.clk_speed = frequency_;
46#ifdef USE_ESP32_VARIANT_ESP32S2
47 // workaround for https://github.com/esphome/issues/issues/6718
48 conf.clk_flags = I2C_SCLK_SRC_FLAG_AWARE_DFS;
49#endif
50 esp_err_t err = i2c_param_config(port_, &conf);
51 if (err != ESP_OK) {
52 ESP_LOGW(TAG, "i2c_param_config failed: %s", esp_err_to_name(err));
53 this->mark_failed();
54 return;
55 }
56 if (timeout_ > 0) { // if timeout specified in yaml:
57 if (timeout_ > 13000) {
58 ESP_LOGW(TAG, "i2c timeout of %" PRIu32 "us greater than max of 13ms on esp-idf, setting to max", timeout_);
59 timeout_ = 13000;
60 }
61 err = i2c_set_timeout(port_, timeout_ * 80); // unit: APB 80MHz clock cycle
62 if (err != ESP_OK) {
63 ESP_LOGW(TAG, "i2c_set_timeout failed: %s", esp_err_to_name(err));
64 this->mark_failed();
65 return;
66 } else {
67 ESP_LOGV(TAG, "i2c_timeout set to %" PRIu32 " ticks (%" PRIu32 " us)", timeout_ * 80, timeout_);
68 }
69 }
70 err = i2c_driver_install(port_, I2C_MODE_MASTER, 0, 0, 0);
71 if (err != ESP_OK) {
72 ESP_LOGW(TAG, "i2c_driver_install failed: %s", esp_err_to_name(err));
73 this->mark_failed();
74 return;
75 }
76 initialized_ = true;
77 if (this->scan_) {
78 ESP_LOGV(TAG, "Scanning bus for active devices");
79 this->i2c_scan_();
80 }
81}
83 ESP_LOGCONFIG(TAG, "I2C Bus:");
84 ESP_LOGCONFIG(TAG,
85 " SDA Pin: GPIO%u\n"
86 " SCL Pin: GPIO%u\n"
87 " Frequency: %" PRIu32 " Hz",
88 this->sda_pin_, this->scl_pin_, this->frequency_);
89 if (timeout_ > 0) {
90 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 "us", this->timeout_);
91 }
92 switch (this->recovery_result_) {
94 ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
95 break;
97 ESP_LOGCONFIG(TAG, " Recovery: failed, SCL is held low on the bus");
98 break;
100 ESP_LOGCONFIG(TAG, " Recovery: failed, SDA is held low on the bus");
101 break;
102 }
103 if (this->scan_) {
104 ESP_LOGI(TAG, "Results from bus scan:");
105 if (scan_results_.empty()) {
106 ESP_LOGI(TAG, "Found no devices");
107 } else {
108 for (const auto &s : scan_results_) {
109 if (s.second) {
110 ESP_LOGI(TAG, "Found device at address 0x%02X", s.first);
111 } else {
112 ESP_LOGE(TAG, "Unknown error at address 0x%02X", s.first);
113 }
114 }
115 }
116 }
117}
118
119ErrorCode IDFI2CBus::readv(uint8_t address, ReadBuffer *buffers, size_t cnt) {
120 // logging is only enabled with vv level, if warnings are shown the caller
121 // should log them
122 if (!initialized_) {
123 ESP_LOGVV(TAG, "i2c bus not initialized!");
125 }
126 i2c_cmd_handle_t cmd = i2c_cmd_link_create();
127 esp_err_t err = i2c_master_start(cmd);
128 if (err != ESP_OK) {
129 ESP_LOGVV(TAG, "RX from %02X master start failed: %s", address, esp_err_to_name(err));
130 i2c_cmd_link_delete(cmd);
131 return ERROR_UNKNOWN;
132 }
133 err = i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_READ, true);
134 if (err != ESP_OK) {
135 ESP_LOGVV(TAG, "RX from %02X address write failed: %s", address, esp_err_to_name(err));
136 i2c_cmd_link_delete(cmd);
137 return ERROR_UNKNOWN;
138 }
139 for (size_t i = 0; i < cnt; i++) {
140 const auto &buf = buffers[i];
141 if (buf.len == 0)
142 continue;
143 err = i2c_master_read(cmd, buf.data, buf.len, i == cnt - 1 ? I2C_MASTER_LAST_NACK : I2C_MASTER_ACK);
144 if (err != ESP_OK) {
145 ESP_LOGVV(TAG, "RX from %02X data read failed: %s", address, esp_err_to_name(err));
146 i2c_cmd_link_delete(cmd);
147 return ERROR_UNKNOWN;
148 }
149 }
150 err = i2c_master_stop(cmd);
151 if (err != ESP_OK) {
152 ESP_LOGVV(TAG, "RX from %02X stop failed: %s", address, esp_err_to_name(err));
153 i2c_cmd_link_delete(cmd);
154 return ERROR_UNKNOWN;
155 }
156 err = i2c_master_cmd_begin(port_, cmd, 20 / portTICK_PERIOD_MS);
157 // i2c_master_cmd_begin() will block for a whole second if no ack:
158 // https://github.com/espressif/esp-idf/issues/4999
159 i2c_cmd_link_delete(cmd);
160 if (err == ESP_FAIL) {
161 // transfer not acked
162 ESP_LOGVV(TAG, "RX from %02X failed: not acked", address);
164 } else if (err == ESP_ERR_TIMEOUT) {
165 ESP_LOGVV(TAG, "RX from %02X failed: timeout", address);
166 return ERROR_TIMEOUT;
167 } else if (err != ESP_OK) {
168 ESP_LOGVV(TAG, "RX from %02X failed: %s", address, esp_err_to_name(err));
169 return ERROR_UNKNOWN;
170 }
171
172#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
173 char debug_buf[4];
174 std::string debug_hex;
175
176 for (size_t i = 0; i < cnt; i++) {
177 const auto &buf = buffers[i];
178 for (size_t j = 0; j < buf.len; j++) {
179 snprintf(debug_buf, sizeof(debug_buf), "%02X", buf.data[j]);
180 debug_hex += debug_buf;
181 }
182 }
183 ESP_LOGVV(TAG, "0x%02X RX %s", address, debug_hex.c_str());
184#endif
185
186 return ERROR_OK;
187}
188ErrorCode IDFI2CBus::writev(uint8_t address, WriteBuffer *buffers, size_t cnt, bool stop) {
189 // logging is only enabled with vv level, if warnings are shown the caller
190 // should log them
191 if (!initialized_) {
192 ESP_LOGVV(TAG, "i2c bus not initialized!");
194 }
195
196#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
197 char debug_buf[4];
198 std::string debug_hex;
199
200 for (size_t i = 0; i < cnt; i++) {
201 const auto &buf = buffers[i];
202 for (size_t j = 0; j < buf.len; j++) {
203 snprintf(debug_buf, sizeof(debug_buf), "%02X", buf.data[j]);
204 debug_hex += debug_buf;
205 }
206 }
207 ESP_LOGVV(TAG, "0x%02X TX %s", address, debug_hex.c_str());
208#endif
209
210 i2c_cmd_handle_t cmd = i2c_cmd_link_create();
211 esp_err_t err = i2c_master_start(cmd);
212 if (err != ESP_OK) {
213 ESP_LOGVV(TAG, "TX to %02X master start failed: %s", address, esp_err_to_name(err));
214 i2c_cmd_link_delete(cmd);
215 return ERROR_UNKNOWN;
216 }
217 err = i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, true);
218 if (err != ESP_OK) {
219 ESP_LOGVV(TAG, "TX to %02X address write failed: %s", address, esp_err_to_name(err));
220 i2c_cmd_link_delete(cmd);
221 return ERROR_UNKNOWN;
222 }
223 for (size_t i = 0; i < cnt; i++) {
224 const auto &buf = buffers[i];
225 if (buf.len == 0)
226 continue;
227 err = i2c_master_write(cmd, buf.data, buf.len, true);
228 if (err != ESP_OK) {
229 ESP_LOGVV(TAG, "TX to %02X data write failed: %s", address, esp_err_to_name(err));
230 i2c_cmd_link_delete(cmd);
231 return ERROR_UNKNOWN;
232 }
233 }
234 if (stop) {
235 err = i2c_master_stop(cmd);
236 if (err != ESP_OK) {
237 ESP_LOGVV(TAG, "TX to %02X master stop failed: %s", address, esp_err_to_name(err));
238 i2c_cmd_link_delete(cmd);
239 return ERROR_UNKNOWN;
240 }
241 }
242 err = i2c_master_cmd_begin(port_, cmd, 20 / portTICK_PERIOD_MS);
243 i2c_cmd_link_delete(cmd);
244 if (err == ESP_FAIL) {
245 // transfer not acked
246 ESP_LOGVV(TAG, "TX to %02X failed: not acked", address);
248 } else if (err == ESP_ERR_TIMEOUT) {
249 ESP_LOGVV(TAG, "TX to %02X failed: timeout", address);
250 return ERROR_TIMEOUT;
251 } else if (err != ESP_OK) {
252 ESP_LOGVV(TAG, "TX to %02X failed: %s", address, esp_err_to_name(err));
253 return ERROR_UNKNOWN;
254 }
255 return ERROR_OK;
256}
257
261void IDFI2CBus::recover_() {
262 ESP_LOGI(TAG, "Performing bus recovery");
263
264 const gpio_num_t scl_pin = static_cast<gpio_num_t>(scl_pin_);
265 const gpio_num_t sda_pin = static_cast<gpio_num_t>(sda_pin_);
266
267 // For the upcoming operations, target for a 60kHz toggle frequency.
268 // 1000kHz is the maximum frequency for I2C running in standard-mode,
269 // but lower frequencies are not a problem.
270 // Note: the timing that is used here is chosen manually, to get
271 // results that are close to the timing that can be archieved by the
272 // implementation for the Arduino framework.
273 const auto half_period_usec = 7;
274
275 // Configure SCL pin for open drain input/output, with a pull up resistor.
276 gpio_set_level(scl_pin, 1);
277 gpio_config_t scl_config{};
278 scl_config.pin_bit_mask = 1ULL << scl_pin_;
279 scl_config.mode = GPIO_MODE_INPUT_OUTPUT_OD;
280 scl_config.pull_up_en = GPIO_PULLUP_ENABLE;
281 scl_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
282 scl_config.intr_type = GPIO_INTR_DISABLE;
283 gpio_config(&scl_config);
284
285 // Configure SDA pin for open drain input/output, with a pull up resistor.
286 gpio_set_level(sda_pin, 1);
287 gpio_config_t sda_conf{};
288 sda_conf.pin_bit_mask = 1ULL << sda_pin_;
289 sda_conf.mode = GPIO_MODE_INPUT_OUTPUT_OD;
290 sda_conf.pull_up_en = GPIO_PULLUP_ENABLE;
291 sda_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
292 sda_conf.intr_type = GPIO_INTR_DISABLE;
293 gpio_config(&sda_conf);
294
295 // If SCL is pulled low on the I2C bus, then some device is interfering
296 // with the SCL line. In that case, the I2C bus cannot be recovered.
297 delayMicroseconds(half_period_usec);
298 if (gpio_get_level(scl_pin) == 0) {
299 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW on the bus");
300 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
301 return;
302 }
303
304 // From the specification:
305 // "If the data line (SDA) is stuck LOW, send nine clock pulses. The
306 // device that held the bus LOW should release it sometime within
307 // those nine clocks."
308 // We don't really have to detect if SDA is stuck low. We'll simply send
309 // nine clock pulses here, just in case SDA is stuck. Actual checks on
310 // the SDA line status will be done after the clock pulses.
311 for (auto i = 0; i < 9; i++) {
312 gpio_set_level(scl_pin, 0);
313 delayMicroseconds(half_period_usec);
314 gpio_set_level(scl_pin, 1);
315 delayMicroseconds(half_period_usec);
316
317 // When SCL is kept LOW at this point, we might be looking at a device
318 // that applies clock stretching. Wait for the release of the SCL line,
319 // but not forever. There is no specification for the maximum allowed
320 // time. We yield and reset the WDT, so as to avoid triggering reset.
321 // No point in trying to recover the bus by forcing a uC reset. Bus
322 // should recover in a few ms or less else not likely to recovery at
323 // all.
324 auto wait = 250;
325 while (wait-- && gpio_get_level(scl_pin) == 0) {
326 App.feed_wdt();
327 delayMicroseconds(half_period_usec * 2);
328 }
329 if (gpio_get_level(scl_pin) == 0) {
330 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW during clock pulse cycle");
331 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
332 return;
333 }
334 }
335
336 // By now, any stuck device ought to have sent all remaining bits of its
337 // transaction, meaning that it should have freed up the SDA line, resulting
338 // in SDA being pulled up.
339 if (gpio_get_level(sda_pin) == 0) {
340 ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
341 recovery_result_ = RECOVERY_FAILED_SDA_LOW;
342 return;
343 }
344
345 // From the specification:
346 // "I2C-bus compatible devices must reset their bus logic on receipt of
347 // a START or repeated START condition such that they all anticipate
348 // the sending of a target address, even if these START conditions are
349 // not positioned according to the proper format."
350 // While the 9 clock pulses from above might have drained all bits of a
351 // single byte within a transaction, a device might have more bytes to
352 // transmit. So here we'll generate a START condition to snap the device
353 // out of this state.
354 // SCL and SDA are already high at this point, so we can generate a START
355 // condition by making the SDA signal LOW.
356 delayMicroseconds(half_period_usec);
357 gpio_set_level(sda_pin, 0);
358
359 // From the specification:
360 // "A START condition immediately followed by a STOP condition (void
361 // message) is an illegal format. Many devices however are designed to
362 // operate properly under this condition."
363 // Finally, we'll bring the I2C bus into a starting state by generating
364 // a STOP condition.
365 delayMicroseconds(half_period_usec);
366 gpio_set_level(sda_pin, 1);
367
368 recovery_result_ = RECOVERY_COMPLETED;
369}
370
371} // namespace i2c
372} // namespace esphome
373
374#endif // USE_ESP_IDF
uint8_t address
Definition bl0906.h:4
void feed_wdt(uint32_t time=0)
virtual void mark_failed()
Mark this component as failed.
bool scan_
Should we scan ? Can be set in the yaml.
Definition i2c_bus.h:108
std::vector< std::pair< uint8_t, bool > > scan_results_
array containing scan results
Definition i2c_bus.h:107
void i2c_scan_()
Scans the I2C bus for devices.
Definition i2c_bus.h:97
ErrorCode readv(uint8_t address, ReadBuffer *buffers, size_t cnt) override
ErrorCode writev(uint8_t address, WriteBuffer *buffers, size_t cnt, bool stop) override
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:11
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
@ ERROR_TIMEOUT
timeout while waiting to receive bytes
Definition i2c_bus.h:16
@ ERROR_NOT_ACKNOWLEDGED
I2C bus acknowledgment not received.
Definition i2c_bus.h:15
@ ERROR_NOT_INITIALIZED
call method to a not initialized bus
Definition i2c_bus.h:17
@ ERROR_UNKNOWN
miscellaneous I2C error during execution
Definition i2c_bus.h:19
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition core.cpp:31
Application App
Global storage of Application pointer - only one Application can exist.
the ReadBuffer structure stores a pointer to a read buffer and its length
Definition i2c_bus.h:24
the WriteBuffer structure stores a pointer to a write buffer and its length
Definition i2c_bus.h:30