SOLVED--Why time reset to its synchronization time value after resetting arduino

Hi, my code works wery well without any problem. It pulls PC time during the synchronization and put it to RTC, system time is set based on RTC time, no problem until now.

The problem appears when I reset Arduino by clicking reset button on it. Or the same thing happens when I cycle the power to arduino. The time that I see on LCD turns back to the time when the code is uploaded to arduino.

The long code is attached. The main part related to time synchronization is below.

Any recommendations?

RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
 DateTime now = RTC.now(); 
 setTime(now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());

Note that I’ve another code which does not have this problem. It is using RTC as well, however as I’m not using TimeAlarms library it does not use setTime command. It is like below:

RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
 DateTime now = RTC.now();

Irrigation_and_Curtain_System_with_TimeAlarm_Library.ino (20 KB)

You’ve put the compile time as constants in your code.

What did you expect to happen?

I just edited the first message to add my comment about my second code that works fine. The problem is why it does not happen in my other code. It keeps the time when I cycle the power or click reset button.

Note that I've another code which does not have this problem.
The problem is why it does not happen in my other code. It keeps the time when I cycle the power or click reset button.

Based on the two snippets you posted, we can not help you. The RTC.adjust() in both snippets call for the time to be reset to the original compile time per the avr built in macros DATE and TIME. The use of the time library or time alarms and the setTime() function do not explain the difference.

RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
 DateTime now = RTC.now(); 
 setTime(now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());
RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
 DateTime now = RTC.now();

Post two simple, complete code examples which demonstrate the two behaviors.

Ok, found it. The main reason is using RTC.adjust code will copy PC time to RTC when PC is available. If PC is not available RTC will use the time that it was connected the last time. As system time is taken from RTC, it will show a previous date/time

So I solve the problem by uploading the code with RTC.adjust first, RTC time is set correctly. Then I comment the line with RTC.adjust code, then upload again. In this case the next time RTC time is not adjusted again, it keeps counting time, so system time continue to get the right time from RTC.