Automatic clock adjustment Arduino
Automatic adjustment of the clock time
The models of the clock device use real-time clocks DS1307, DS3231. Unfortunately, all these time sources have an error. For example, DS1307 have an error of 5-20 seconds per day. This amounts to up to two hours per year. The DS3231 time source is much more accurate, but also has an error of 1-4 seconds per day.
The accuracy of the clock can be significantly improved if automatic time adjustments are made at certain time intervals. For watches using DS1307, this algorithm described below reduces the error to 1 second per day (6 minutes per year).
Description of the algorithm
We determine the error of the clock. We synchronize the clock with the exact astronomical time and wait for a few days. Then we compare the time on our watch with the source of the exact time and divide the error by the number of days for which the error has accumulated. For example, in 5 days the clock is 40 seconds behind. This means that the daily error of the clock is 8 seconds.
The essence of the automatic clock correction algorithm is that the automatic clock correction mechanism is triggered in two cases:
- When the clock is turned on;
- Every 24 hours of continuous operation.
- The date and exact time of the last clock adjustment are stored in non-volatile memory. This will allow you to calculate the magnitude of the stroke correction even in the event of a sudden loss of power to the watch. Or when the clock is turned off for a long time.
- The value of the clock stroke correction is determined as follows:
- the daily correction of the clock is read from the non-volatile memory;
- the Julian date of the last adjustment of the clock is determined — for this purpose, the date and exact time of the last adjustment of the clock are pre-read from the non-volatile memory;
- the Julian date of the current system time of the clock is determined;
- both dates are translated into the number of hours;
- The difference in Julian dates is the number of hours that have elapsed since the last time adjustment. This difference is multiplied by the hourly correction of the clock, which is the value of the correction of the clock in seconds;
- next, the current system time is converted to seconds, added up with the time correction and converted back to the date and exact time;
- a new system time is being set;
- The date and time of the last time adjustment is stored in the non-volatile memory of the Arduino.
A subroutine for adjusting the time of the clock
By following the link, you can download an archive with a text file containing a subroutine for adjusting the time of the clock.