I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".
Here you can see an excerpt from the example provided for the pcf8523 real-time clock:
#include "RTClib.h"
RTC_PCF8523 rtc;
void setup () {
while (!Serial) {
delay(1); // for Leonardo/Micro/Zero
}
Serial.begin(57600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (! rtc.initialized()) {
Serial.println("RTC is NOT running!");
}
}
void loop () {
DateTime now = rtc.now();
Serial.print(now.year(), DEC);
/*
do some more stuff
*/
}
In the beginning of loop() they wrote:
DateTime now = rtc.now();
Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right? This appears inefficient to me.
I thought about rewriting it this way:
static DateTime now; // static declaration, executed only once
now = rtc.now(); // assignment to "now" every time loop() starts over
In this case "new" should be allocated on the stack like a global variable, right?
I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.
Link to the library: https://github.com/adafruit/RTClib
Thank you! :-)
EDIT: For some reason I CAN NOT declare DateTime now;
in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.
DateTime now;
in global scope”: what happens if you do so? A compilation error? Incorrect run-time behavior? I tried and it compiles just fine (but I have no RTC for testing).DateTime now = rtc.now()
might have utilize "copy elision", so it gets constructed directly intonow
variable and therefore it's faster than your approach (as you effectively blocked this possibility - so it has to create temporary object and copy it into now variable).Setup()
.Setup()
starts withSerial.begin(9600); Serial.println("test");
Blinking the builtin-led doesn't work either.