15#include "soft_i2c_master.h"
18 void (*delay)(uint32_t us),
bool pullup)
28soft_i2c_master::~soft_i2c_master()
31 _sda.gpioMode(GPIO::INPUT);
32 _scl.gpioMode(GPIO::INPUT);
35int16_t soft_i2c_master::i2cRead(uint16_t addr, uint8_t *rxbuf, uint16_t len,
39 if (!send_start())
return -1;
43 if (!write_byte(addr)) {
44 if (sendStop) send_stop();
47 for (uint16_t i = 0; i < len; ++i) {
48 rxbuf[i] = read_byte(i==(len-1));
50 if (sendStop) send_stop();
54int16_t soft_i2c_master::i2cWrite(uint16_t addr, uint8_t *txbuf, uint16_t len,
58 if (!send_start())
return -1;
61 if (!write_byte(addr)) {
62 if (sendStop) send_stop();
65 for (uint16_t i = 0; i < len; ++i) {
66 if (!write_byte(txbuf[i])) {
67 if (sendStop) send_stop();
71 if (sendStop) send_stop();
75void soft_i2c_master::setSpeed(uint32_t hz) {
84void soft_i2c_master::init()
86 uint16_t mode = GPIO::INPUT |
87 GPIO::OUTPUT_OPEN_DRAIN |
99uint8_t soft_i2c_master::read_byte(
bool nack)
102 for (uint8_t bit = 0; bit < 8; ++bit) {
110bool soft_i2c_master::write_byte(uint8_t
byte)
112 for (uint8_t bit = 0; bit < 8; ++bit) {
113 write_bit(
byte & 0x80);
119bool soft_i2c_master::read_bit()
123 _sda.gpioWrite(HIGH);
125 _scl.gpioWrite(HIGH);
127 while (_scl.gpioRead() == LOW) _delay(_us);
128 bool bit = _sda.gpioRead();
133bool soft_i2c_master::write_bit(
bool bit)
139 _scl.gpioWrite(HIGH);
141 do _delay(_us);
while (_scl.gpioRead() == LOW);
145bool soft_i2c_master::send_start()
147 if (!check_bus_idle())
return false;
153void soft_i2c_master::send_stop()
159 _scl.gpioWrite(HIGH);
161 do _delay(_us);
while (_scl.gpioRead() == LOW);
162 _sda.gpioWrite(HIGH);
166bool soft_i2c_master::check_bus_idle() {
168 _scl.gpioWrite(HIGH);
169 _sda.gpioWrite(HIGH);
172 while((_sda.gpioRead() == LOW) && (i < 20)) {
175 _scl.gpioWrite(HIGH);