/***
 *** The Example has no copyright and can be used by anyone.
 *** The following example is based on Device File Package
 *** required to compile the macro definitions used.
 *** The Device File Package is available by downloading Atmel Studio 7.
 ***/

/***
 *** In this example the aim is to start a 1s timer.
 *** RTC in calendar mode (mode 2) using periodic event and 
 *** using the XOSC32K 1KHZ output as closk source
 *** The RTC is also configured to trigger an ADC start conversion every seconds
 *** based on the Periodic Event PEREO7
 ***/
void RTC_Init(void) {
 /*** Enable RTC APB Clock ***/
 MCLK->APBAMASK.reg |= MCLK_APBAMASK_RTC;

 /*** clock for RTC : XOSC32K 1KHZ output as closk source ***/
 OSC32KCTRL->RTCCTRL.bit.RTCSEL = OSC32KCTRL_RTCCTRL_RTCSEL(OSC32KCTRL_RTCCTRL_RTCSEL_XOSC1K_Val);

 /*** Disable RTC: Enable Protected ***/
 RTC->MODE2.CTRLA.reg &= ~(RTC_MODE2_CTRLA_ENABLE);
 /*** (write synchronized) ***/
 while(RTC->MODE2.SYNCBUSY.reg & RTC_MODE2_SYNCBUSY_ENABLE);

 /*** Reset RTC ***/
 RTC->MODE2.CTRLA.reg = (RTC_MODE2_CTRLA_SWRST);
 /*** (write synchronized) ***/
 while(RTC->MODE2.SYNCBUSY.reg & RTC_MODE2_SYNCBUSY_SWRST);

 /*** RTC in mode 2 (calendar) 
  *** using a prescaler value of 1024, dividing the 1KHz input clock source 
  *** getting a 1s clock.
  ***/
 RTC->MODE2.CTRLA.reg = RTC_MODE2_CTRLA_PRESCALER(RTC_MODE2_CTRLA_PRESCALER_DIV1024_Val)|
                        RTC_MODE2_CTRLA_MODE(RTC_MODE2_CTRLA_MODE_CLOCK_Val);

 /*** RTC Periodic event control ***/
 RTC->MODE2.EVCTRL.reg = RTC_MODE2_EVCTRL_PEREO7;

 /*** Clear All interrupt flags ***/
 RTC->MODE2.INTFLAG.reg = 0xFFFF;

 /*** set interrupt every seconds ***/
 RTC->MODE2.INTENSET.reg |= RTC_MODE2_INTENSET_PER7;

 /*** Enable RTC interrupt at core Level (NVIC) set the highest priority ***/
 NVIC_EnableIRQ(RTC_IRQn);
 NVIC_SetPriority(RTC_IRQn,0);

 /*** change the clocksync ***/
 RTC->MODE2.CTRLA.bit.CLOCKSYNC = 1;
 /*** (write synchronized) ***/
 while(RTC->MODE2.SYNCBUSY.bit.CLOCKSYNC);

 /*** Re Enable RTC (Enable Protected) ***/
 RTC->MODE2.CTRLA.bit.ENABLE = 1;
 /*** (write synchronized) ***/
 while(RTC->MODE2.SYNCBUSY.bit.ENABLE);
}

/***
 *** RTC Interrupt Handler
 *** Interrupt Clear
 ***/

void RTC_Handler (void) 
{
 RTC->MODE2.INTFLAG.reg;
 /*** Check if an ALARM interrupt appeared ***/
 /*** Clear ALARM interrupt flag ***/
 RTC->MODE2.INTFLAG.reg |= RTC_MODE2_INTENSET_PER7;
}