Working with i2c in multiple cpp files

02 Aug 2010

I'm trying to get data from an accelerometer and a magnetometer. I've got all the code for the acceleromter in acc.cpp, and I'd like to do the same for the magnetometer in mag.cpp. Where should I put the "I2C i2c(p28, p27);" statement? Can I do it globally? Do I have to do it locally?

02 Aug 2010

Hi Alex,

You can actually do either, depending on your preferred approach:

1) Make it global so they share the same "interface". If you instance an I2C interface somewhere in a .cpp file, and make a header file that declares it so you can #include it in multiple places. This is just a standard technique to split things across multiple files, as described in this post.

2) Give them each their own I2C interface that shares the same physical I2C interface. The way the mbed interfaces for I2C and SPI are designed, it is possible to have multiple "virtual" interfaces that live on the same physical interface. So in your example, create an interface for the accelerometer, and one for the magnetometer, and just use the same pins for each. This should just work, and is meant to give a much better system, where each interface can have it's own I2C interface independent of anyone else (easier to write reusable libraries), yet they share the same physical interface (easier to use).

Try 2) if you can, and report back if you have any questions.

Simon