Avoid multiple instances when declaring variables in classes

In my project I've got multiple classes that need time and a LCD display

  1. the class "Screen" which displays the time and date.
  2. the class "Menu" which allows you to change the time and date.

When declaring the variables I ran into an error (multiple instances).

So now i've got this

in Menu.cpp

...
#include <DS3232RTC.h>
DS3232RTC ScreenRTC;
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Screenlcd(0x27, 16, 2);
...
Screen::Screen() {
  Screenlcd.init();
  setSyncProvider(ScreenRTC.get);
}

And in Screen.cpp:

...
#include <DS3232RTC.h>
DS3232RTC MenuRTC;
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Menulcd(0x27, 16, 2);
...
Menu::Menu() {
    Menulcd.init();
    setSyncProvider(MenuRTC.get);
}

Is this the correct way or is there a way to create a single instance which can be used by both of them?

Please show the complete code (all files). Please post the full error message; please use code tags for those as well.

It does not make sense to have the same LCD in both files.

Let me rephrase the question before it looks like an XY problem...

Theres only one lcd screen and one RTC module which I want to use in both classes.
So the code I provided is only about declaring the LCD and RTC module in two classes.

The code I have now doesn't throw any errors but that doesn't mean it the right way.

Hello

Here is an example how you can do that, sorry it's in French but search "lcd" I think you will easily understand. Basically, the lcd is created in the main sketch and initialized normally in setup(), then a reference to this lcd is given to the Moteur class by using

// link LCD to the Moteur class
Moteur::lcd( lcd );

Your incomplete post does not provide sufficient insight into the full structure of your code. So, it's impossible to give definitive advise. But, a couple ideas might be ...

  1. Put the RTC in it's own class that has a public function to provide the time ... ie getTime()

  2. Make the RTC global in your main code and pass it to the classes as a refence.

Declare the lcd and rtc as static and make sure that they are public so they can be accessed from outside the class.
https://en.cppreference.com/w/cpp/language/static

Thanks that was exactly what I was looking for!

DS3232RTC ScreenRTC;
LiquidCrystal_I2C Screenlcd(0x27, 16, 2);

shouldn't both of these lines be in your main .ino/cpp file and presumably there is a (loop).h file containing

extern DS3232RTC         ScreenRTC;
extern LiquidCrystal_I2C Screenlcd;

included in other files as required

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.