I am using an Arduino Uno.
**Questions: **
- Does having DateTime now = RTC.now in the loop create a now object every loop?
- Is DateTime now = RTC.now in the loop reading the RTC each loop?
3 . If so, is there a way to not create this object every loop?
I want to use the Time Library and not update to the RTC every loop.
Use setSyncProvider and setSyncInterval to update to RTC every 5 seconds.
When I do move DateTime now = RTC.now out of the loop I get error:
"request for member 'hour' in 'now', which is of non-class type 'time_t() {aka long unsigned int()}'
Serial.print(now.hour());"
Purpose of code below is to better understand functions and variables of the Time Library and RTCLib.
In setup():
Set RTC to 5:10:30
Set Time Library to 9:27:05
Every 5 seconds Time Library gets sync'd to RTC
Evert 7 seconds Time Library gets set back to 9:27:05
#include "RTClib.h"#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>
RTC_DS1307 RTC;
unsigned long LastUnSyncTime = 0;
time_t time_provider()
{
return RTC.now().unixtime();
}
void setup() {
Serial.begin(9600);
Wire.begin(); //sets up the I2C
RTC.begin(); //initializes the I2C to the RTC
// Set the RTC Time to 5:10:30 Nov 3 2020
RTC.adjust(DateTime(2020,11,3,5,10,30));
setSyncProvider(time_provider); //sets Time Library to RTC time
setSyncInterval(5); //sync Time Library to RTC every 5 seconds
//Set Arduino Time Library different than RTC time 9:27:05 so see how sync works
setTime(9, 27, 05, 4, 07, 2015);
if(timeStatus()!= timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop() {
if ((millis() - LastUnSyncTime) > 7000)
{
Serial.println("-----------------------------");
setTime(9, 27, 05, 4, 07, 2015);
LastUnSyncTime = millis();
}
DateTime now = RTC.now(); // Creating now object every loop?
//Print Time Lib Times
Serial.print("hour: ");
Serial.print(hour());
Serial.println();
Serial.print("minute: ");
Serial.print(minute());
Serial.println();
Serial.print("seconds: ");
Serial.print(second());
Serial.println();
Serial.println();
//Print RTC time
Serial.print("now.hour: ");
Serial.print(now.hour());
Serial.println();
Serial.print("now.minute: ");
Serial.print(now.minute());
Serial.println();
Serial.print("now.second: ");
Serial.print(now.second());
Serial.println();
Serial.println();
Serial.println();
delay(1000);
}