/***
 *** 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.
 ***/

void configure_32K_clocks(void)
{

 /*** Enable XOSC32K 
  *** Enable XTAL drive
  *** Enable 1KHz output
  *** Enable 32KHz output
  *** Set a Start up time to 5 which represents around 4s start-up time.
  *** Enable GCLK2 with XOSC32K as clock source for TC0 (eventually) 
  ***/
 OSC32KCTRL->XOSC32K.reg = OSC32KCTRL_XOSC32K_ENABLE|
                           OSC32KCTRL_XOSC32K_XTALEN|
                           OSC32KCTRL_XOSC32K_EN1K|
                           OSC32KCTRL_XOSC32K_EN32K|
                           OSC32KCTRL_XOSC32K_STARTUP(5);
 while(OSC32KCTRL->STATUS.bit.XOSC32KRDY==0);

 /*** Enable GCLK2 with XOSC32K as clock source for TC0 for ADC 1KHz Triggering ***/
 GCLK->GENCTRL[2].reg = GCLK_GENCTRL_DIV(1) | CURRENT_32KOSC |GCLK_GENCTRL_GENEN;
 /*** (write synchronized) ***/
 while((GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL2));
 GCLK->PCHCTRL[GCLK_TC0].reg = (GCLK_PCHCTRL_CHEN|GCLK_PCHCTRL_GEN_GCLK2);
}