ESPHome 2025.8.2
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
5#include <driver/gpio.h>
6#include <cinttypes>
7#include <cstring>
9#include "esphome/core/hal.h"
11#include "esphome/core/log.h"
12
13namespace esphome {
14namespace i2c {
15
16static const char *const TAG = "i2c.idf";
17
19 static i2c_port_t next_port = I2C_NUM_0;
20 this->port_ = next_port;
21 if (this->port_ == I2C_NUM_MAX) {
22 ESP_LOGE(TAG, "No more than %u buses supported", I2C_NUM_MAX);
23 this->mark_failed();
24 return;
25 }
26
27 if (this->timeout_ > 13000) {
28 ESP_LOGW(TAG, "Using max allowed timeout: 13 ms");
29 this->timeout_ = 13000;
30 }
31
32 this->recover_();
33
34 next_port = (i2c_port_t) (next_port + 1);
35
36 i2c_master_bus_config_t bus_conf{};
37 memset(&bus_conf, 0, sizeof(bus_conf));
38 bus_conf.sda_io_num = gpio_num_t(sda_pin_);
39 bus_conf.scl_io_num = gpio_num_t(scl_pin_);
40 bus_conf.i2c_port = this->port_;
41 bus_conf.glitch_ignore_cnt = 7;
42#if SOC_LP_I2C_SUPPORTED
43 if (this->port_ < SOC_HP_I2C_NUM) {
44 bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
45 } else {
46 bus_conf.lp_source_clk = LP_I2C_SCLK_DEFAULT;
47 }
48#else
49 bus_conf.clk_source = I2C_CLK_SRC_DEFAULT;
50#endif
51 bus_conf.flags.enable_internal_pullup = sda_pullup_enabled_ || scl_pullup_enabled_;
52 esp_err_t err = i2c_new_master_bus(&bus_conf, &this->bus_);
53 if (err != ESP_OK) {
54 ESP_LOGW(TAG, "i2c_new_master_bus failed: %s", esp_err_to_name(err));
55 this->mark_failed();
56 return;
57 }
58
59 i2c_device_config_t dev_conf{};
60 memset(&dev_conf, 0, sizeof(dev_conf));
61 dev_conf.dev_addr_length = I2C_ADDR_BIT_LEN_7;
62 dev_conf.device_address = I2C_DEVICE_ADDRESS_NOT_USED;
63 dev_conf.scl_speed_hz = this->frequency_;
64 dev_conf.scl_wait_us = this->timeout_;
65 err = i2c_master_bus_add_device(this->bus_, &dev_conf, &this->dev_);
66 if (err != ESP_OK) {
67 ESP_LOGW(TAG, "i2c_master_bus_add_device failed: %s", esp_err_to_name(err));
68 this->mark_failed();
69 return;
70 }
71
72 this->initialized_ = true;
73
74 if (this->scan_) {
75 ESP_LOGV(TAG, "Scanning for devices");
76 this->i2c_scan_();
77 }
78}
79
81 ESP_LOGCONFIG(TAG, "I2C Bus:");
82 ESP_LOGCONFIG(TAG,
83 " SDA Pin: GPIO%u\n"
84 " SCL Pin: GPIO%u\n"
85 " Frequency: %" PRIu32 " Hz",
86 this->sda_pin_, this->scl_pin_, this->frequency_);
87 if (timeout_ > 0) {
88 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 "us", this->timeout_);
89 }
90 switch (this->recovery_result_) {
92 ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
93 break;
95 ESP_LOGCONFIG(TAG, " Recovery: failed, SCL is held low on the bus");
96 break;
98 ESP_LOGCONFIG(TAG, " Recovery: failed, SDA is held low on the bus");
99 break;
100 }
101 if (this->scan_) {
102 ESP_LOGCONFIG(TAG, "Results from bus scan:");
103 if (scan_results_.empty()) {
104 ESP_LOGCONFIG(TAG, "Found no devices");
105 } else {
106 for (const auto &s : scan_results_) {
107 if (s.second) {
108 ESP_LOGCONFIG(TAG, "Found device at address 0x%02X", s.first);
109 } else {
110 ESP_LOGE(TAG, "Unknown error at address 0x%02X", s.first);
111 }
112 }
113 }
114 }
115}
116
117ErrorCode IDFI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
118 size_t read_count) {
119 // logging is only enabled with v level, if warnings are shown the caller
120 // should log them
121 if (!initialized_) {
122 ESP_LOGW(TAG, "i2c bus not initialized!");
124 }
125
126 i2c_operation_job_t jobs[8]{};
127 size_t num_jobs = 0;
128 uint8_t write_addr = (address << 1) | I2C_MASTER_WRITE;
129 uint8_t read_addr = (address << 1) | I2C_MASTER_READ;
130 ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", write_count, read_count);
131 if (read_count == 0 && write_count == 0) {
132 // basically just a bus probe. Send a start, address and stop
133 ESP_LOGV(TAG, "0x%02X BUS PROBE", address);
134 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
135 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
136 jobs[num_jobs].write.ack_check = true;
137 jobs[num_jobs].write.data = &write_addr;
138 jobs[num_jobs++].write.total_bytes = 1;
139 } else {
140 if (write_count != 0) {
141 ESP_LOGV(TAG, "0x%02X TX %s", address, format_hex_pretty(write_buffer, write_count).c_str());
142 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
143 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
144 jobs[num_jobs].write.ack_check = true;
145 jobs[num_jobs].write.data = &write_addr;
146 jobs[num_jobs++].write.total_bytes = 1;
147 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
148 jobs[num_jobs].write.ack_check = true;
149 jobs[num_jobs].write.data = (uint8_t *) write_buffer;
150 jobs[num_jobs++].write.total_bytes = write_count;
151 }
152 if (read_count != 0) {
153 ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
154 jobs[num_jobs++].command = I2C_MASTER_CMD_START;
155 jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
156 jobs[num_jobs].write.ack_check = true;
157 jobs[num_jobs].write.data = &read_addr;
158 jobs[num_jobs++].write.total_bytes = 1;
159 if (read_count > 1) {
160 jobs[num_jobs].command = I2C_MASTER_CMD_READ;
161 jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
162 jobs[num_jobs].read.data = read_buffer;
163 jobs[num_jobs++].read.total_bytes = read_count - 1;
164 }
165 jobs[num_jobs].command = I2C_MASTER_CMD_READ;
166 jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
167 jobs[num_jobs].read.data = read_buffer + read_count - 1;
168 jobs[num_jobs++].read.total_bytes = 1;
169 }
170 }
171 jobs[num_jobs++].command = I2C_MASTER_CMD_STOP;
172 ESP_LOGV(TAG, "Sending %zu jobs", num_jobs);
173 esp_err_t err = i2c_master_execute_defined_operations(this->dev_, jobs, num_jobs, 20);
174 if (err == ESP_ERR_INVALID_STATE) {
175 ESP_LOGV(TAG, "TX to %02X failed: not acked", address);
177 } else if (err == ESP_ERR_TIMEOUT) {
178 ESP_LOGV(TAG, "TX to %02X failed: timeout", address);
179 return ERROR_TIMEOUT;
180 } else if (err != ESP_OK) {
181 ESP_LOGV(TAG, "TX to %02X failed: %s", address, esp_err_to_name(err));
182 return ERROR_UNKNOWN;
183 }
184 return ERROR_OK;
185}
186
190void IDFI2CBus::recover_() {
191 ESP_LOGI(TAG, "Performing bus recovery");
192
193 const auto scl_pin = static_cast<gpio_num_t>(scl_pin_);
194 const auto sda_pin = static_cast<gpio_num_t>(sda_pin_);
195
196 // For the upcoming operations, target for a 60kHz toggle frequency.
197 // 1000kHz is the maximum frequency for I2C running in standard-mode,
198 // but lower frequencies are not a problem.
199 // Note: the timing that is used here is chosen manually, to get
200 // results that are close to the timing that can be archieved by the
201 // implementation for the Arduino framework.
202 const auto half_period_usec = 7;
203
204 // Configure SCL pin for open drain input/output, with a pull up resistor.
205 gpio_set_level(scl_pin, 1);
206 gpio_config_t scl_config{};
207 scl_config.pin_bit_mask = 1ULL << scl_pin_;
208 scl_config.mode = GPIO_MODE_INPUT_OUTPUT_OD;
209 scl_config.pull_up_en = GPIO_PULLUP_ENABLE;
210 scl_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
211 scl_config.intr_type = GPIO_INTR_DISABLE;
212 gpio_config(&scl_config);
213
214 // Configure SDA pin for open drain input/output, with a pull up resistor.
215 gpio_set_level(sda_pin, 1);
216 gpio_config_t sda_conf{};
217 sda_conf.pin_bit_mask = 1ULL << sda_pin_;
218 sda_conf.mode = GPIO_MODE_INPUT_OUTPUT_OD;
219 sda_conf.pull_up_en = GPIO_PULLUP_ENABLE;
220 sda_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
221 sda_conf.intr_type = GPIO_INTR_DISABLE;
222 gpio_config(&sda_conf);
223
224 // If SCL is pulled low on the I2C bus, then some device is interfering
225 // with the SCL line. In that case, the I2C bus cannot be recovered.
226 delayMicroseconds(half_period_usec);
227 if (gpio_get_level(scl_pin) == 0) {
228 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW on the bus");
229 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
230 return;
231 }
232
233 // From the specification:
234 // "If the data line (SDA) is stuck LOW, send nine clock pulses. The
235 // device that held the bus LOW should release it sometime within
236 // those nine clocks."
237 // We don't really have to detect if SDA is stuck low. We'll simply send
238 // nine clock pulses here, just in case SDA is stuck. Actual checks on
239 // the SDA line status will be done after the clock pulses.
240 for (auto i = 0; i < 9; i++) {
241 gpio_set_level(scl_pin, 0);
242 delayMicroseconds(half_period_usec);
243 gpio_set_level(scl_pin, 1);
244 delayMicroseconds(half_period_usec);
245
246 // When SCL is kept LOW at this point, we might be looking at a device
247 // that applies clock stretching. Wait for the release of the SCL line,
248 // but not forever. There is no specification for the maximum allowed
249 // time. We yield and reset the WDT, so as to avoid triggering reset.
250 // No point in trying to recover the bus by forcing a uC reset. Bus
251 // should recover in a few ms or less else not likely to recovery at
252 // all.
253 auto wait = 250;
254 while (wait-- && gpio_get_level(scl_pin) == 0) {
255 App.feed_wdt();
256 delayMicroseconds(half_period_usec * 2);
257 }
258 if (gpio_get_level(scl_pin) == 0) {
259 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW during clock pulse cycle");
260 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
261 return;
262 }
263 }
264
265 // By now, any stuck device ought to have sent all remaining bits of its
266 // transaction, meaning that it should have freed up the SDA line, resulting
267 // in SDA being pulled up.
268 if (gpio_get_level(sda_pin) == 0) {
269 ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
270 recovery_result_ = RECOVERY_FAILED_SDA_LOW;
271 return;
272 }
273
274 // From the specification:
275 // "I2C-bus compatible devices must reset their bus logic on receipt of
276 // a START or repeated START condition such that they all anticipate
277 // the sending of a target address, even if these START conditions are
278 // not positioned according to the proper format."
279 // While the 9 clock pulses from above might have drained all bits of a
280 // single byte within a transaction, a device might have more bytes to
281 // transmit. So here we'll generate a START condition to snap the device
282 // out of this state.
283 // SCL and SDA are already high at this point, so we can generate a START
284 // condition by making the SDA signal LOW.
285 delayMicroseconds(half_period_usec);
286 gpio_set_level(sda_pin, 0);
287
288 // From the specification:
289 // "A START condition immediately followed by a STOP condition (void
290 // message) is an illegal format. Many devices however are designed to
291 // operate properly under this condition."
292 // Finally, we'll bring the I2C bus into a starting state by generating
293 // a STOP condition.
294 delayMicroseconds(half_period_usec);
295 gpio_set_level(sda_pin, 1);
296
297 recovery_result_ = RECOVERY_COMPLETED;
298}
299
300} // namespace i2c
301} // namespace esphome
302#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:106
std::vector< std::pair< uint8_t, bool > > scan_results_
array containing scan results
Definition i2c_bus.h:105
i2c_master_bus_handle_t bus_
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
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:14
@ ERROR_TIMEOUT
timeout while waiting to receive bytes
Definition i2c_bus.h:19
@ ERROR_NOT_ACKNOWLEDGED
I2C bus acknowledgment not received.
Definition i2c_bus.h:18
@ ERROR_NOT_INITIALIZED
call method to a not initialized bus
Definition i2c_bus.h:20
@ ERROR_UNKNOWN
miscellaneous I2C error during execution
Definition i2c_bus.h:22
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
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:280
Application App
Global storage of Application pointer - only one Application can exist.