jrowberg / i2cdevlib

I2C device library collection for AVR/Arduino or other C++-based MCUs
http://www.i2cdevlib.com
3.92k stars 7.52k forks source link

begin() method for i2cdevlib device classes to support Arduino users #352

Open metd01567 opened 6 years ago

metd01567 commented 6 years ago

The Arduino "new" operator doesn't support parameters to constructors. I run a simple factory at startup, creating as many ADS1115 objects as needed for my current project. I plan to expand the factory with additional device types as I create new projects.

There is an Arduino convention for classes to provide a "begin" method. "begin" finishes construction, usually called from an application's "setup" function. To be consistent, existing i2cdevlib public constructors would need a matching begin() method if there are parameters. That shouldn't affect current library users. For consistency, it would be best to update all of the device classes, not just the ADS1115. For portability, it should be applied to all processor types. Not a simple request.

I've changed the following in my ADS1115 library. It's a little ugly with code copied from the true constructor. It would be better to create a private method for calling from both places.

Add to ADS115.h: void begin(uint8_t address);

Add to ADS1115.cpp: void ADS1115::begin(uint8_t address) { devAddr = address; }

metd01567 commented 6 years ago

Allowing access by a friend class (ADS1115Wrapper?) would do if that's your style. For portability across platforms, it would still need to be a global i2cdevlib change. I like the public begin() better, it's about the same amount of work.

metd01567 commented 6 years ago

I started this just to get an ADS1115 working with the Arduino IDE. Along the way I used dynamic allocation. I now understand that dynamic allocation is anathema to Arduino IDE users.

I've got a workaround for now, and I've decided to move to a different IDE. So I'm OK without my suggested i2cdevlib changes. It's up to you, if you want to follow Arduino conventions you could add begin methods at some point.