I2C Using Wire Library

Platform: Arduino Due
Protocol: I2C
Library: Wire

I have three questions:

  • I wrote a library to communicate to a sensor using I2C using the Wire library. I included the wire library in the cpp file of the library (#include <Wire.h>) and then the initialize function of the class made the board join the bus as a master using Wire.begin();. I have some serial debug commands within my main .ino file. This code works perfectly on Arduino UNO but when I upload it to the Due the serial commands don't show in the serial monitor. I found out that removing Wire.begin(); from the class initialize function and putting it in setup() function of the main .ino file corrects the problem. Any idea why this is happening? I'd like to make the library independent and have all initializations there.
  • What if I have multiple libraries and all have Wire.begin(); running when they initialize? Would that cause any problems and is it a bad practice?
  • In the I2C protocol the receiver device sends an acknowledgement. Is there any way for me to check if the ack was received or not using the Wire library?

Thanks in advance :slight_smile:

from the class initialize function

The one that you failed to post?

Any idea why this is happening?

Nope. I ordered a crystal ball, but, wouldn't you know it, it's New Years Day in China, and shipping from China takes forever anyway. I've got a projected arrival data of the 12th of never. Hang on, though, and I'll get back to you when it arrives.

What if I have multiple libraries and all have Wire.begin(); running when they initialize? Would that cause any problems and is it a bad practice?

Maybe and definitely.

Is there any way for me to check if the ack was received or not using the Wire library?

Yes.

from the class initialize function

The one that you failed to post?

...

abc::abc() {
Wire.begin();
}

Thanks for the informative answers.

I came across another problem:

Wire.read(); keeps reading the last value it read even when I remove the device.

This library seems to not be working very well on the Due, any alternatives?

Figured out the NACK bit. It is returned for value/address by Wire.endTransmission();

Reference: Wire - Arduino Reference

The hardware that Wire.begin() sets up is NOT ready when your constructor is called. That's why the work is not done in the Wire constructor.

You can't call begin() in your constructor. You need a begin() method, too, that you call AFTER init() has been called to set up the hardware.

This library seems to not be working very well on the Due, any alternatives?

Proper usage. Don't disconnect I2C devices while the Arduino is powered. You might as well be whacking it with a hammer.