3 Using the RTC for Real Time Tracking
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:
- The required oscillator may be enabled in the CLKCTRL module and selected as the RTC clock source (ideally a highly accurate 32.768 kHz oscillator)
- The RTC may be allowed to run in standby
- The prescaler may be set to an appropriate value, to give a count increment once per second (e.g. for a 32.768 kHz oscillator, choose DIV32768)
- The period may be set to the desired overflow interval
- The RTC Interrupt flags may be cleared and the overflow interrupt enabled
- Finally, the RTC may be enabled to start counting
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.