Another I2C Bus to Manage Multiple Devices..Coding Questions/Methods

Hi,

I’m working on developing some type of I2C Bus or multiple I2C Device Manager Wrapper code. I’ve read a handful of posts across the web and not sure I found anything I liked.

The way I have my code is that I write a Class for each physical I2Cdevice. This way, I can use different devices in different projects. Anyway, I’m looking for a way to manage the I2C bus with these multiple classes but want to avoid all of the I2CDeviceBus.config=Device1Config in each devices’ methods to ensure I’m communicating on the right bus. To me, there should be a more elegant way to code this. Is there a way to automatically switch the I2C bus configuration whenever any one device’s methods is invoked?

For example: pseudocode would work like this.


//setup Hardware
I2Cbus = New I2CDevice;//this is the "bus"
Device1 = New Device1(I2CBus;//Pass the bus into the device-Has its own I2CConfig
Device2 = New Device1(I2CBus);//Pass the bus into the device-has Its own I2CConfig
//End Hardware

Device1.Method1();//When this is called, it should automatically switch configuration1
Device2.Method3();//Configuration2
Device1.Method2();//Back to Configuration1


I’m trying to avoid duplicate code at the beginning of every Device Method. Currently, I would have some Internal Method for each class, but then this is redundant in each class.


Private CheckI2CConfig(deviceConfig);
{
If (I2CBus.Config != deviceConfig)
{I2CBus.Config = deviceConfig;}
}
Method1()
{
CheckI2CConfig(DeviceConifig);
//Do i2C stuff
}


Though this isn’t the worst thing, but I’m looking for a more elegant way to contain this all. It also would clean up the code IMO.

I’m open to any ideas!
Thanks

@ Gismofx -

if your code (or your wrapper class) are correct, and your hardware is setup correctly, i think it will also work correctly. Just make sure there is no same address on your bus

Thanks. Yes, I’m just looking for a more elegant way to code it. Whenever I create a new method in a device class, I need to include the

 at the beginning of each method and the each device class needs to contain that method. Maybe I could inherit that method from another class.

Could this help you ?
https://www.ghielectronics.com/community/codeshare/entry/130