Using more than one lib using the same driver

Hello,

I' written several drivers using Wire.h for several peripherals. I actually pass nothing to the constructors, for instance:

LCD myLcd = LCD();

in the setup() function I call my begin() method like this:

myLcd.begin(byte slave_number);

In this begin, I do this:

Wire.begin();
mySlaveNumber = slave_number;

It works fine for one peripheral, but how do I do with several peripherals?

@pfeuh, your topic has been moved to a more suitable location.

You use different addresses. Most libraries know the default address for the chip they handle so you don't always have to specify an address, but there is an address for each chip.

Sometimes you have to specify the address in the constructor:
LIBRARY myInstance(address);
or
LIBRARY myInstance = LIBRARY(address);

Sometimes you set the address in .begin():

LIBRARY myInstance;
void setup()
{
  Wire.begin();
  myInstance.begin(address);
}

And sometimes there is a member function for setting the address:

LIBRARY myInstance;
void setup()
{
  Wire.begin();
  myInstance.begin();
  myInstance.setAddress(address);
}

Thank you sterretje.

Thank you johnwasser, I understand. Some last questions: For each device (with a different slave number), do I have to insert a
Wire.begin();?
Is it safe to call it one time per device? In fact that was my first question. I read somewhere that begin() method has to be called only one time.

Just my 2 cents but Wire.begin() belongs in setup(), not in a class. It's the initialisation of the I2C hardware.

I feel the same, but Wire.begin() is also used in most of arduino classes' begin method, am I wrong?

I absolutely support that.

@pfeuh By the way, Sparkfun has a nice How To Write a Great Library

Thanks a lot. Answer of my question is in your SparkFun link.

No. You only need one Wire.begin() for all I2C/Wire/TWI devices.

I looked at the Wire library and it appears that it would be OK to call Wire.begin() more than once, as long as they are all done before any of the libraries tries to send or receive data. Better to require the Wire.begin() call before the libraries

1 Like

And, I really wish library authors would not do it that way. For maximum flexibility, the library should accept a reference to the proper class type and let the user configure the object outside of the library.

So, a library that does Serial I/O would accept a reference to a Stream object. A library that needs SPI would accept a reference to a SPIClass object. A library that needs I2C would accept a reference to TwoWire object. Etc, etc.

Doing the above would be really helpful to those using boards with multiple Serial, I2C, SPI ports.

I may be wrong, but it looks like just including Wire library with #include <Wire.h> open it. I say that because I just commented wire.begin() in every libs of my code and it works still.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.