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