3 RTC Overflow Interrupt

This code example shows how to use the RTC with overflow interrupt enabled to toggle an LED. The overflow period is 500 ms. The on-board LED will be toggled each time the overflow interrupt occurs.

To operate the RTC, the source clock for the RTC counter must be configured before enabling the RTC peripheral and the desired actions (interrupt requests, output events). In this example, the 32.768 kHz external oscillator is used as the source clock.

To configure the oscillator, first, it must be disabled by clearing the ENABLE bit in the CLKCTRL.XOSC32KCTRLA register:

Figure 3-1. CLKCTRL.XOSC32KCTRLA – Clear the ENABLE Bit
uint8_t temp;
temp = CLKCTRL.XOSC32KCTRLA;
temp &= ~CLKCTRL_ENABLE_bm;
ccp_write_io((void*)&CLKCTRL.XOSC32KCTRLA, temp);

The user must then wait for the corresponding status bit to become ‘0’:

Figure 3-2. CLKCTRL.MCLKSTATUS – Read XOSC32KS
while(CLKCTRL.MCLKSTATUS & CLKCTRL_XOSC32KS_bm)
{
	;
}

Select the external oscillator by clearing the SEL bit in the CLKCTRL.XOSC32KCTRLA register:

Figure 3-3. CLKCTRL.XOSC32KCTRLA – Clear the SEL Bit
temp = CLKCTRL.XOSC32KCTRLA;
temp &= ~CLKCTRL_SEL_bm;
ccp_write_io((void*)&CLKCTRL.XOSC32KCTRLA, temp);

Then, enable the oscillator by setting the ENABLE bit in the CLKCTRL.XOSC32KCTRLA register:

temp = CLKCTRL.XOSC32KCTRLA;
temp |= CLKCTRL_ENABLE_bm;
ccp_write_io((void*)&CLKCTRL.XOSC32KCTRLA, temp);

Afterward, the user must wait for all registers to be synchronized:

Figure 3-4. RTC.STATUS
while (RTC.STATUS > 0)
{
	;
}

The RTC period is set in the RTC.PER register:

Figure 3-5. RTC.PER – Set Period

The 32.768 kHz External Crystal Oscillator clock is selected in the RTC.CLKSEL register:

Figure 3-6. RTC.CLKSEL – Clock Selection
RTC.CLKSEL = RTC_CLKSEL_TOSC32K_gc;

To enable the RTC to also run in Debug mode, the DBGRUN bit is set in the RTC.DBGCTRL register:

Figure 3-7. RTC.CLKSEL – Set the DBGRUN Bit
RTC.DBGCTRL |= RTC_DBGRUN_bm;

The RTC prescaler is set in the RTC.CTRLA register. Set the RUNSTDBY bit in RTC.CTRLA to enable the RTC to also run in Standby mode. Set the RTCEN bit in RTC.CTRLA to enable the RTC.

Figure 3-8. RTC.CTRLA – Set the Prescaler, RUNSTDBY Bit, RTCEN Bit
RTC.CTRLA = RTC_PRESCALER_DIV32_gc | RTC_RTCEN_bm | RTC_RUNSTDBY_bm;

Enable the overflow interrupt by setting the OVF bit in the RTC.INTCTRL register:

Figure 3-9. RTC.INTCTRL – Set the OVF Bit
RTC.INTCTRL |= RTC_OVF_bm;

For the interrupt to occur, the global interrupts must be enabled:

sei();

The Interrupt Service Routine (ISR) for the RTC overflow will toggle an LED in the example below:

ISR(RTC_CNT_vect)
{
    RTC.INTFLAGS = RTC_OVF_bm;
    LED0_toggle();
}
Note: Clear the OVF bit from the RTC.INTFLAGS register by writing a ‘1’ to it inside the ISR function.
Tip: The full code example is available in the Appendix section.

An MCC generated code example for AVR128DA48, with the same functionality as the one described in this section, can be found here: