Skip to main content
2 of 2
added 757 characters in body
Michel Keijzers
  • 13k
  • 7
  • 42
  • 59

You don't need to use the static keyword.

The cleanest solution is to define DateTime outside of the loop function:

DateTime now;

This will allocate the memory, and call the constructor of the class DateTime initializing it.

In case you would need a basic variable (like an int), you should initialize it, like:

int now = 0;

When you use it in setup or loop you use the created instance (without the class name to declare it):

void loop() {
   ...
   now = rtc.now();
}

Also, find a better name for now, because the variable is the same as the rtc's function now.

Update

after your comment, it cannot be used as a global variable:

I didn't try it myself, but I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point. Actually, it's quite bad practice.

Anyway, one way to circumvent and stick as much to what I wrote above, is to use a pointer instead:

RTC_PCF8523* rtc = NULL;

Than you create an empty pointer, without calling the constructor. You will do this at the end of setup:

void setup() {
   ...
   rtc = new RTC_PCF8523();
}

This will cause the variable to be put on the stack.

Than when using it, you call:

now = rtc->now();

Note you have to use the -> notation, as rtc is a pointer.

Michel Keijzers
  • 13k
  • 7
  • 42
  • 59