The RTC peripheral can be used to keep track of real time. The period is configurable, so it is not necessary to generate an interrupt every second; this enables a decrease in power consumption. An overflow needs to be generated only when the current time is required e.g. for timestamp generation. The period can be changed from anywhere between one second to more than 18 hours.
The RTC may be configured as follows:
Additionally, an ISR may be defined for the RTC overflow interrupt vector (RTC_CNT_vect), to complete the time update and any other required periodic tasks such as a sensor measurement and timestamp string generation. Two subroutines are used to update the time. They use a time struct as defined below.
typedef struct{
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t date;
uint8_t month;
uint16_t year;
}time;
The 'update time' subroutine increments the 'second' by the defined number of seconds in the period, and checks for the necessity to increment the higher value members, i.e. 'minute' is incremented if 'second' is larger than or equal to 60, and so on. The complete functionality of the subroutine is depicted in the following figure.
The 'not a leap year?' subroutine is used by the 'update time' subroutine when checking whether 'month' needs to be incremented during February. It returns true if it is not a leap year, i.e. February has 28 days, and false if it is a leap year, i.e. February has 29 days. Its calculations can be seen in the figure below.