Let's study Python

Ensure accurate timekeeping with RTC modules by structuring your code correctly.

# Python time.clock_settime 사용법

When working with RTC (Real-time Clock) modules like DS1302 in Arduino projects, it is essential to understand how time is set and maintained. By uploading Code 1 to the Arduino board, you can observe the time set in Code 1 displaying on the serial monitor, showing the time progressing. Now, let’s turn off the serial monitor and turn it back on. How will it be displayed? One might expect the time to resume from where it left off when the serial monitor was turned off, but in reality, this is not the case. The time will revert back to the one set in the code. The reason for this behavior lies within the code itself. Even though the RTC module may calculate time, the moment the board is reset or the power is disconnected and reconnected, the code responsible for setting the time will run again. This results in erasing the calculated time and resetting it to the specified time in the code.

To prevent this from happening and to ensure that the RTC module continues to keep time accurately even after power cycles or resets, the solution is simple. First, upload the code that sets the time (Code 1) and then upload the rest of the code without the time-setting part. In other words, comment out the 3 lines of code mentioned above and upload the modified code.

“`cpp
Code 1-1
#include

DS1302 RTC(2, 3, 4);

void setup() {
RTC.halt(false);
RTC.writeProtect(false);
Serial.begin(9600);
// RTC.setDOW(THURSDAY);
// RTC.setTime(14, 30, 0);
// RTC.setDate(24, 3, 2021);
}

void loop() {
Time now = RTC.getTime();
Serial.print(now.year);
Serial.print(“/”);
Serial.print(now.mon);
Serial.print(“/”);
Serial.println(now.date);

Serial.print(now.hour);
Serial.print(“:”);
Serial.print(now.min);
Serial.print(“:”);
Serial.println(now.sec);
}
“`

By following this approach, if you upload Code 1 and then immediately upload Code 1-1, you will notice that the Arduino board retains the time even after resets or power cycles (provided that the RTC module has a coin cell battery installed).

In summary, when working with RTC modules like DS1302, it is crucial to understand how time setting works and how to ensure accurate timekeeping even after power interruptions. By structuring the code correctly and managing the time-setting part, you can maintain precise timekeeping functionality in your Arduino projects.