11 years, 7 months ago.

how do i define and use a global instance of defined mbed class?

below is my setup. I want to use mbed i2c pre-defined class, with only a single i2c_2 object(since they use the same pins), in multiple files. but i cant get it to work. any help?

bad code

-----------------global.h------------------
extern I2C i2c_2(p28, p27);
--------------------------global.cpp------------------
I2C i2c_2(p28, p27);
------------------------main.cpp------------------
#include global.h
#include mbed.h

void main(){
      i2c_2.write(....);
}
-------------------------eeprom.h------------------
#include global.h
void eeprom();
-------------------------eeprom.cpp------------------
#include eeprom.h

void eeprom(){
      i2c_2.write(....);
}
-------------------------lights.h------------------
#include global.h
void lights();
------------------------lights.cpp------------------
#include lights.h

void lights(){
      i2c_2.write(....);
}
------------------------

2 Answers

11 years, 7 months ago.

I think if you leave out the (p28, p27) on the external declaration in global.h it should work. What error do you get?

11 years, 7 months ago.

[solved] whoops. ended up figuring out my problem. here's the correct the notation. [solved]

passing objects through multiple functions

mbed_class myobject;

function2(mbed_class *myobject){
     myobject->mymember(..);
}

function1(mbed_class *myobject){
    function2(myobject);   
   //function2(&myobject);   //i used to have that "&"
}

main(){
      myobject.mymember(..);
      function1(&myobject); 
}

ended up not using global instance.

That is indeed the best way afaik, that said there also is not really a reason to stick to one object per pair of pins. Sure a bit less memory usage, but that is really a small difference. So if you have lets say 3 sensors on a single I2C bus it isn't a problem to give each of them a different I2C object.

posted by Erik - 28 Mar 2013

so erik, what youre saying is you can have multiple I2C objects that all point to the same 2 i2c pins? i never tried that, i assumed it all has to use the same object, b/c that object called out the 2 i2c pins.

posted by jonathan liu 29 Mar 2013

Exactly yes, you can have multiple I2C objects pointing to the same I2C pins. And they can have for example different clock speeds, then it will automatically switch clock speed depending on the one you are using.

posted by Erik - 29 Mar 2013