I have two projects that have the same source code. Both projects have a I2C display, that is initialized like
Liquidcrystal_I2C mylcd(0x3F,2,1... etc.
where 0x3F is the address of the display. However: the two displays have two different addresses. It is easy to let the program find the address, but that takes a few lines of code in setup(). If I initialize the LCD inside the setup() function, it is invisible to loop() and other functions.
Of course I can use #ifdef, but I would rather do it automagically.
paai:
I have two projects that have the same source code. Both projects have a I2C display, that is initialized like
Liquidcrystal_I2C mylcd(0x3F,2,1... etc.
where 0x3F is the address of the display. However: the two displays have two different addresses. It is easy to let the program find the address, but that takes a few lines of code in setup(). If I initialize the LCD inside the setup() function, it is invisible to loop() and other functions.
Of course I can use #ifdef, but I would rather do it automagically.
create a global pointer to a LiquidCrystal_I2C object, create the instance in setup() and copy the global pointer to the 'new' lcd object...
something like this (just an example I had handy...)
class Shapes{
public:
Shapes() {};
int area() {return _length * _width;};
void setLength(int length){ _length = length;};
void setWidth(int width){_width = width;};
private:
int _width, _length;
};
Shapes* myPtr; //<< global pointer
int myValue = 10;
void setup()
{
Serial.begin(9600);
Shapes* myBox = new Shapes(); // create a new instance of Shapes pointed to by myBox
myPtr = myBox; //<< copy the pointer to the new object
myBox->setLength(10);
(*myBox).setWidth(5);
Serial.println(myBox->area());
}
void loop()
{
myPtr->setLength(myValue+=5); // I can now manipulate the object
Serial.println(myPtr->area()); // and reference it globally
delay(1000);
}
So like this:
liquidCrystal_I2C* lcd;
void setup()
{
// find your I2C device
// Create an I2C object:
liquidCrystal_I2C* myLcd = new liquidCrystal_I2C();
etc...
// copy th pointer
lcd = myLcd;
// etc...
lcd->print("hey, this works");