bitbank2 / BitBang_I2C

A software I2C implementation to run on any GPIO pins on any system
GNU General Public License v3.0
235 stars 31 forks source link

Performance tweak #1

Closed Jingjok86 closed 4 years ago

Jingjok86 commented 4 years ago

Hi,

Thanks for the BitBang library, I have used it in an ESP32 project, where I needed high speed soft-I2C comms on GPIOs.

I found that the I2C performance on ESP32 can be almost doubled (to about 1 Mhz), if you change the function

void sleep_us(int iDelay)
...
#else
  delayMicroseconds(iDelay);
#endif
...

to

#else
  if (iDelay > 0) {
    delayMicroseconds(iDelay);
  }
#endif

this avoids calling the delayMicroseconds, which has some overhead as it always reads the millis()

( iClock needs to be set to 1000000 in I2CInit for this to have an effect )

Also, there seems to be a small bug in I2CInit :

if (iClock >= 1000000)
  iDelay = 0;
else if (iClock >= 800000)
  iDelay = 1;
else if (iClock >= 400000)
  iDelay = 2;
else if (iClock >= 100000)
  iDelay = 10;
else iDelay = 1000000 / iClock

the last line would hang the comms, if iClock is set to less than 100000

bitbank2 commented 4 years ago

I'm glad you found it useful. I'm actually working on a new version with those fixes already in :)

I'm going to include my "multi_bitbang" features in a single library too.