ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
i2c_bus_arduino.cpp
Go to the documentation of this file.
1#if defined(USE_ARDUINO) && !defined(USE_ESP32)
2
3#include "i2c_bus_arduino.h"
4#include <Arduino.h>
5#include <cstring>
8#include "esphome/core/log.h"
9
10namespace esphome {
11namespace i2c {
12
13static const char *const TAG = "i2c.arduino";
14
15// Maximum bytes to log in hex format (truncates larger transfers)
16static constexpr size_t I2C_MAX_LOG_BYTES = 32;
17
19 recover_();
20
21#if defined(USE_ESP8266)
22 wire_ = new TwoWire(); // NOLINT(cppcoreguidelines-owning-memory)
23#elif defined(USE_RP2040)
24 static bool first = true;
25 if (first) {
26 wire_ = &Wire;
27 first = false;
28 } else {
29 wire_ = &Wire1; // NOLINT(cppcoreguidelines-owning-memory)
30 }
31#endif
32
33 this->set_pins_and_clock_();
34
35 this->initialized_ = true;
36 if (this->scan_) {
37 ESP_LOGV(TAG, "Scanning bus for active devices");
38 this->i2c_scan_();
39 }
40}
41
42void ArduinoI2CBus::set_pins_and_clock_() {
43#ifdef USE_RP2040
44 wire_->setSDA(this->sda_pin_);
45 wire_->setSCL(this->scl_pin_);
46 wire_->begin();
47#else
48 wire_->begin(static_cast<int>(sda_pin_), static_cast<int>(scl_pin_));
49#endif
50 if (timeout_ > 0) { // if timeout specified in yaml
51#if defined(USE_ESP8266)
52 // https://github.com/esp8266/Arduino/blob/master/libraries/Wire/Wire.h
53 wire_->setClockStretchLimit(timeout_); // unit: us
54#elif defined(USE_RP2040)
55 // https://github.com/earlephilhower/ArduinoCore-API/blob/e37df85425e0ac020bfad226d927f9b00d2e0fb7/api/Stream.h
56 wire_->setTimeout(timeout_ / 1000); // unit: ms
57#endif
58 }
59 wire_->setClock(frequency_);
60}
61
63 ESP_LOGCONFIG(TAG, "I2C Bus:");
64 ESP_LOGCONFIG(TAG,
65 " SDA Pin: GPIO%u\n"
66 " SCL Pin: GPIO%u\n"
67 " Frequency: %u Hz",
68 this->sda_pin_, this->scl_pin_, this->frequency_);
69 if (timeout_ > 0) {
70#if defined(USE_ESP8266)
71 ESP_LOGCONFIG(TAG, " Timeout: %u us", this->timeout_);
72#elif defined(USE_RP2040)
73 ESP_LOGCONFIG(TAG, " Timeout: %u ms", this->timeout_ / 1000);
74#endif
75 }
76 switch (this->recovery_result_) {
78 ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
79 break;
81 ESP_LOGCONFIG(TAG, " Recovery: failed, SCL is held low on the bus");
82 break;
84 ESP_LOGCONFIG(TAG, " Recovery: failed, SDA is held low on the bus");
85 break;
86 }
87 if (this->scan_) {
88 ESP_LOGI(TAG, "Results from bus scan:");
89 if (scan_results_.empty()) {
90 ESP_LOGI(TAG, "Found no devices");
91 } else {
92 for (const auto &s : scan_results_) {
93 if (s.second) {
94 ESP_LOGI(TAG, "Found device at address 0x%02X", s.first);
95 } else {
96 ESP_LOGE(TAG, "Unknown error at address 0x%02X", s.first);
97 }
98 }
99 }
100 }
101}
102
103ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
104 uint8_t *read_buffer, size_t read_count) {
105#if defined(USE_ESP8266)
106 this->set_pins_and_clock_(); // reconfigure Wire global state in case there are multiple instances
107#endif
108 if (!initialized_) {
109 ESP_LOGD(TAG, "i2c bus not initialized!");
111 }
112
113#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
114 char hex_buf[format_hex_pretty_size(I2C_MAX_LOG_BYTES)];
115 ESP_LOGV(TAG, "0x%02X TX %s", address, format_hex_pretty_to(hex_buf, write_buffer, write_count));
116#endif
117
118 uint8_t status = 0;
119 if (write_count != 0 || read_count == 0) {
120 wire_->beginTransmission(address);
121 size_t ret = wire_->write(write_buffer, write_count);
122 if (ret != write_count) {
123 ESP_LOGV(TAG, "TX failed");
124 return ERROR_UNKNOWN;
125 }
126 status = wire_->endTransmission(read_count == 0);
127 }
128 if (status == 0 && read_count != 0) {
129 size_t ret2 = wire_->requestFrom(address, read_count, true);
130 if (ret2 != read_count) {
131 ESP_LOGVV(TAG, "RX %u from %02X failed with error %u", read_count, address, ret2);
132 return ERROR_TIMEOUT;
133 }
134 for (size_t j = 0; j != read_count; j++)
135 read_buffer[j] = wire_->read();
136 }
137 switch (status) {
138 case 0:
139 return ERROR_OK;
140 case 1:
141 // transmit buffer not large enough
142 ESP_LOGVV(TAG, "TX failed: buffer not large enough");
143 return ERROR_UNKNOWN;
144 case 2:
145 case 3:
146 ESP_LOGVV(TAG, "TX failed: not acknowledged: %d", status);
148 case 5:
149 ESP_LOGVV(TAG, "TX failed: timeout");
150 return ERROR_UNKNOWN;
151 case 4:
152 default:
153 ESP_LOGVV(TAG, "TX failed: unknown error %u", status);
154 return ERROR_UNKNOWN;
155 }
156}
157
161void ArduinoI2CBus::recover_() {
162 ESP_LOGI(TAG, "Performing bus recovery");
163
164 // For the upcoming operations, target for a 100kHz toggle frequency.
165 // This is the maximum frequency for I2C running in standard-mode.
166 // The actual frequency will be lower, because of the additional
167 // function calls that are done, but that is no problem.
168 const auto half_period_usec = 1000000 / 100000 / 2;
169
170 // Activate input and pull up resistor for the SCL pin.
171 pinMode(scl_pin_, INPUT_PULLUP); // NOLINT
172
173 // This should make the signal on the line HIGH. If SCL is pulled low
174 // on the I2C bus however, then some device is interfering with the SCL
175 // line. In that case, the I2C bus cannot be recovered.
176 delayMicroseconds(half_period_usec);
177 if (digitalRead(scl_pin_) == LOW) { // NOLINT
178 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW on the bus");
179 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
180 return;
181 }
182
183 // From the specification:
184 // "If the data line (SDA) is stuck LOW, send nine clock pulses. The
185 // device that held the bus LOW should release it sometime within
186 // those nine clocks."
187 // We don't really have to detect if SDA is stuck low. We'll simply send
188 // nine clock pulses here, just in case SDA is stuck. Actual checks on
189 // the SDA line status will be done after the clock pulses.
190
191 // Make sure that switching to output mode will make SCL low, just in
192 // case other code has setup the pin for a HIGH signal.
193 digitalWrite(scl_pin_, LOW); // NOLINT
194
195 delayMicroseconds(half_period_usec);
196 for (auto i = 0; i < 9; i++) {
197 // Release pull up resistor and switch to output to make the signal LOW.
198 pinMode(scl_pin_, INPUT); // NOLINT
199 pinMode(scl_pin_, OUTPUT); // NOLINT
200 delayMicroseconds(half_period_usec);
201
202 // Release output and activate pull up resistor to make the signal HIGH.
203 pinMode(scl_pin_, INPUT); // NOLINT
204 pinMode(scl_pin_, INPUT_PULLUP); // NOLINT
205 delayMicroseconds(half_period_usec);
206
207 // When SCL is kept LOW at this point, we might be looking at a device
208 // that applies clock stretching. Wait for the release of the SCL line,
209 // but not forever. There is no specification for the maximum allowed
210 // time. We yield and reset the WDT, so as to avoid triggering reset.
211 // No point in trying to recover the bus by forcing a uC reset. Bus
212 // should recover in a few ms or less else not likely to recovery at
213 // all.
214 auto wait = 250;
215 while (wait-- && digitalRead(scl_pin_) == LOW) { // NOLINT
216 App.feed_wdt();
217 delayMicroseconds(half_period_usec * 2);
218 }
219 if (digitalRead(scl_pin_) == LOW) { // NOLINT
220 ESP_LOGE(TAG, "Recovery failed: SCL is held LOW during clock pulse cycle");
221 recovery_result_ = RECOVERY_FAILED_SCL_LOW;
222 return;
223 }
224 }
225
226 // Activate input and pull resistor for the SDA pin, so we can verify
227 // that SDA is pulled HIGH in the following step.
228 pinMode(sda_pin_, INPUT_PULLUP); // NOLINT
229 digitalWrite(sda_pin_, LOW); // NOLINT
230
231 // By now, any stuck device ought to have sent all remaining bits of its
232 // transaction, meaning that it should have freed up the SDA line, resulting
233 // in SDA being pulled up.
234 if (digitalRead(sda_pin_) == LOW) { // NOLINT
235 ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
236 recovery_result_ = RECOVERY_FAILED_SDA_LOW;
237 return;
238 }
239
240 // From the specification:
241 // "I2C-bus compatible devices must reset their bus logic on receipt of
242 // a START or repeated START condition such that they all anticipate
243 // the sending of a target address, even if these START conditions are
244 // not positioned according to the proper format."
245 // While the 9 clock pulses from above might have drained all bits of a
246 // single byte within a transaction, a device might have more bytes to
247 // transmit. So here we'll generate a START condition to snap the device
248 // out of this state.
249 // SCL and SDA are already high at this point, so we can generate a START
250 // condition by making the SDA signal LOW.
251 delayMicroseconds(half_period_usec);
252 pinMode(sda_pin_, INPUT); // NOLINT
253 pinMode(sda_pin_, OUTPUT); // NOLINT
254
255 // From the specification:
256 // "A START condition immediately followed by a STOP condition (void
257 // message) is an illegal format. Many devices however are designed to
258 // operate properly under this condition."
259 // Finally, we'll bring the I2C bus into a starting state by generating
260 // a STOP condition.
261 delayMicroseconds(half_period_usec);
262 pinMode(sda_pin_, INPUT); // NOLINT
263 pinMode(sda_pin_, INPUT_PULLUP); // NOLINT
264
265 recovery_result_ = RECOVERY_COMPLETED;
266}
267} // namespace i2c
268} // namespace esphome
269
270#endif // defined(USE_ARDUINO) && !defined(USE_ESP32)
uint8_t address
Definition bl0906.h:4
uint8_t status
Definition bl0942.h:8
void feed_wdt(uint32_t time=0)
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer, size_t read_count) override
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
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:28
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:331
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:735
Application App
Global storage of Application pointer - only one Application can exist.