ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
i2c_bus_software.cpp
Go to the documentation of this file.
1#ifdef USE_LIBRETINY
2
3#include "i2c_bus_software.h"
4#include <cinttypes>
5#include "esphome/core/hal.h"
6#include "esphome/core/log.h"
7
8namespace esphome::i2c {
9
10ESPHOME_LOG_TAG(TAG, "i2c.software");
11
12// Maximum bytes to log in hex format (truncates larger transfers)
13static constexpr size_t I2C_MAX_LOG_BYTES = 32;
14// Clock pulses used to free a device that is holding SDA low
15static constexpr uint8_t RECOVERY_CLOCK_PULSES = 9;
16
17// A line is released by switching the pin to input with pull-up and pulled low by driving it as output.
18static inline void release_line(InternalGPIOPin *pin) { pin->pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP); }
19static inline void pull_line_low(InternalGPIOPin *pin) {
20 pin->digital_write(false);
22}
23
25 this->update_half_period_();
26 this->sda_pin_->setup();
27 this->scl_pin_->setup();
28 release_line(this->sda_pin_);
29 release_line(this->scl_pin_);
30 if (!this->recover_()) {
31 // A line that stays low would be read as an ACK for every address and as zero data
32 ESP_LOGE(TAG, "SDA or SCL is held low, the bus cannot be used");
33 this->mark_failed();
34 return;
35 }
36 this->initialized_ = true;
37 if (this->scan_) {
38 ESP_LOGV(TAG, "Scanning bus for active devices");
39 this->i2c_scan_();
40 }
41}
42
44 ESP_LOGCONFIG(TAG, "I2C Bus (software):");
45 LOG_PIN(" SDA Pin: ", this->sda_pin_);
46 LOG_PIN(" SCL Pin: ", this->scl_pin_);
47 ESP_LOGCONFIG(TAG,
48 " Frequency: %" PRIu32 " Hz\n"
49 " Clock stretch timeout: %" PRIu32 " us",
50 this->frequency_, this->timeout_);
51 if (this->recovered_) {
52 ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
53 }
54 this->dump_scan_results_();
55}
56
57// Half of one clock period in microseconds, rounded up. The frequency is validated to be non-zero.
59 this->half_period_us_ = (500000 + this->frequency_ - 1) / this->frequency_;
60}
61
62#ifdef I2C_PORT_FREQUENCY_COUNT
70#endif
71
73 this->timed_out_ = false;
74 // A device may still be stretching the clock, give SCL the configured time to rise before looking at SDA
75 this->release_scl_();
76 // A device that was interrupted in the middle of a transfer can hold SDA low; clock it out.
77 bool clocked = false;
78 for (uint8_t i = 0; i < RECOVERY_CLOCK_PULSES && !this->sda_pin_->digital_read(); i++) {
79 pull_line_low(this->scl_pin_);
81 // wait for the rising edge, the device may stretch the clock
82 if (!this->release_scl_())
83 break;
85 clocked = true;
86 }
87 bool ok = this->sda_pin_->digital_read() && this->scl_pin_->digital_read();
88 if (ok && clocked) {
89 // end the interrupted transfer with a STOP so every device returns to idle
90 this->recovered_ = true;
91 pull_line_low(this->sda_pin_);
93 release_line(this->scl_pin_);
95 release_line(this->sda_pin_);
96 }
97 if (!ok) {
98 ESP_LOGW(TAG, "Bus recovery failed, a line is held low");
99 }
100 this->timed_out_ = false;
101 return ok;
102}
103
104// Release SCL and wait for it to go high, a device may stretch the clock.
106 release_line(this->scl_pin_);
107 uint32_t start = micros();
108 while (!this->scl_pin_->digital_read()) {
109 if (micros() - start > this->timeout_) {
110 this->timed_out_ = true;
111 return false;
112 }
113 }
114 return true;
115}
116
118 // Also generates a repeated start when SCL is low and SDA is released
119 release_line(this->sda_pin_);
120 // After a byte the device may still hold SDA low for its ACK. Without SDA being high before SCL rises there is
121 // no falling edge, so the (repeated) start would not be seen. Wait until the device lets go.
122 uint32_t start = micros();
123 while (!this->sda_pin_->digital_read()) {
124 if (micros() - start > this->timeout_) {
125 this->timed_out_ = true;
126 return;
127 }
128 }
130 this->release_scl_();
132 pull_line_low(this->sda_pin_);
134 pull_line_low(this->scl_pin_);
135}
136
138 if (this->timed_out_) {
139 // SCL is stuck low, a STOP cannot be generated; just release both lines
140 release_line(this->scl_pin_);
141 release_line(this->sda_pin_);
142 return;
143 }
144 pull_line_low(this->sda_pin_);
146 this->release_scl_();
148 release_line(this->sda_pin_);
150}
151
153bool SoftwareI2CBus::write_byte_(uint8_t data) {
154 for (uint8_t mask = 0x80; mask != 0 && !this->timed_out_; mask >>= 1) {
155 if (data & mask) {
156 release_line(this->sda_pin_);
157 } else {
158 pull_line_low(this->sda_pin_);
159 }
161 this->release_scl_();
163 pull_line_low(this->scl_pin_);
164 }
165 if (this->timed_out_)
166 return false;
167 release_line(this->sda_pin_);
169 if (!this->release_scl_())
170 return false;
172 bool ack = !this->sda_pin_->digital_read();
173 pull_line_low(this->scl_pin_);
174 return ack;
175}
176
178 uint8_t data = 0;
179 release_line(this->sda_pin_);
180 for (uint8_t i = 0; i < 8 && !this->timed_out_; i++) {
182 this->release_scl_();
184 data = (data << 1) | (this->sda_pin_->digital_read() ? 1 : 0);
185 pull_line_low(this->scl_pin_);
186 }
187 if (this->timed_out_)
188 return data;
189 if (ack) {
190 pull_line_low(this->sda_pin_);
191 }
193 this->release_scl_();
195 pull_line_low(this->scl_pin_);
196 release_line(this->sda_pin_);
197 return data;
198}
199
200ErrorCode SoftwareI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
201 uint8_t *read_buffer, size_t read_count) {
202 if (!this->initialized_) {
203 ESP_LOGD(TAG, "i2c bus not initialized!");
205 }
206 // After a failed recovery the bus stays blocked until a later attempt frees both lines
207 if (this->bus_stuck_ && !this->recover_()) {
208 return ERROR_TIMEOUT;
209 }
210 this->bus_stuck_ = false;
211
212 ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
213
214 this->timed_out_ = false;
215 ErrorCode err = ERROR_OK;
216 this->start_();
217 // An empty transfer only addresses the device (used by the bus scan)
218 if (write_count != 0 || read_count == 0) {
219 if (!this->write_byte_(address << 1)) {
221 }
222 for (size_t i = 0; err == ERROR_OK && i < write_count; i++) {
223 if (!this->write_byte_(write_buffer[i])) {
224 ESP_LOGVV(TAG, "TX of byte %u to 0x%02X not acknowledged", (unsigned) i, address);
226 }
227 }
228 }
229 if (err == ERROR_OK && read_count != 0) {
230 if (write_count != 0) {
231 this->start_(); // repeated start
232 }
233 if (!this->write_byte_((address << 1) | 1)) {
235 }
236 for (size_t i = 0; err == ERROR_OK && !this->timed_out_ && i < read_count; i++) {
237 read_buffer[i] = this->read_byte_(i + 1 != read_count);
238 }
239 }
240 this->stop_();
241
242 if (this->timed_out_) {
243 ESP_LOGVV(TAG, "Bus line held low during transfer to 0x%02X for more than %" PRIu32 " us", address, this->timeout_);
244 this->bus_stuck_ = !this->recover_();
245 return ERROR_TIMEOUT;
246 }
247 return err;
248}
249
250} // namespace esphome::i2c
251
252#endif // USE_LIBRETINY
uint16_le_t frequency
Definition bl0942.h:6
void mark_failed()
Mark this component as failed.
void pin_mode(gpio::Flags flags) override
Definition gpio.cpp:195
void digital_write(bool value) override
Definition gpio.cpp:215
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 write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer, size_t read_count) override
ErrorCode switch_frequency(uint32_t frequency) override
bool write_byte_(uint8_t data)
Shift out one byte, returns true if the device acknowledged it.
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_INVALID_ARGUMENT
method called invalid argument(s)
Definition i2c_bus.h:16
@ 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
ESPHOME_LOG_TAG(TAG, "i2c")
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
static void uint32_t
uint8_t ack