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:
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
’:
while(CLKCTRL.MCLKSTATUS & CLKCTRL_XOSC32KS_bm) { ; }
Select the external oscillator by clearing the SEL bit in the CLKCTRL.XOSC32KCTRLA register:
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:
while (RTC.STATUS > 0)
{
;
}
The RTC period is set in the RTC.PER register:
The 32.768 kHz External Crystal Oscillator clock is selected in the RTC.CLKSEL register:
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:
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.
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:
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(); }
1
’ to it inside the ISR function.An MCC generated code example for AVR128DA48, with the same functionality as the one described in this section, can be found here: