#include "sensor_soft_i2c.h" #include static void delay(const sensor_soft_i2c_t *p) { p->delay_us(p->context, p->half_period_us); } static int high(const sensor_soft_i2c_t *p) { p->scl(p->context, 1); for (unsigned n = 0; n <= p->stretch_timeout_us; n++) { if (p->read_scl(p->context)) { delay(p); return 0; } p->delay_us(p->context, 1); } return -1; } static int write_bit(const sensor_soft_i2c_t *p, int bit) { p->sda(p->context, bit); delay(p); if (high(p)) return -1; p->scl(p->context, 0); return 0; } static int read_bit(const sensor_soft_i2c_t *p) { p->sda(p->context, 1); delay(p); if (high(p)) return -1; int bit = p->read_sda(p->context) != 0; p->scl(p->context, 0); return bit; } static int write_byte(const sensor_soft_i2c_t *p, uint8_t byte) { for (int n = 7; n >= 0; n--) if (write_bit(p, (byte >> n) & 1)) return -1; return read_bit(p); // ACK=0, NACK=1, bus failure=-1. } int sensor_soft_i2c_transfer(const sensor_soft_i2c_t *p, uint8_t address, uint8_t *data, uint16_t count, bool read) { if (!p || !p->sda || !p->scl || !p->read_sda || !p->read_scl || !p->delay_us || !p->half_period_us || address > 127 || (count && !data)) return -1; p->sda(p->context, 1); if (high(p) || !p->read_sda(p->context)) { p->sda(p->context, 1); p->scl(p->context, 1); return -1; } p->sda(p->context, 0); // START while clock is high. delay(p); p->scl(p->context, 0); int error = write_byte(p, (uint8_t)((address << 1) | read)); for (uint16_t i = 0; i < count && !error; i++) { if (!read) { error = write_byte(p, data[i]); continue; } uint8_t byte = 0; for (unsigned n = 0; n < 8; n++) { int bit = read_bit(p); if (bit < 0) { error = -1; break; } byte = (uint8_t)((byte << 1) | bit); } if (!error) { data[i] = byte; error = write_bit(p, i + 1 == count); // NACK only the final byte. } } // STOP on both success and failure; leave neither line driven low. p->scl(p->context, 0); p->sda(p->context, 0); delay(p); int stop_error = high(p); p->sda(p->context, 1); delay(p); return error ? error : stop_error; }