/***
 *** 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 Several Generic Clock Generators
 *** are configured to provide clock source to different
 *** peripherals of the system:
 *** - GCLK2 provides XOSC32K to TC0 (this requires XOSC32K enabled first)
 *** - GCLK3 provides DFLL to ADC (this requires DFLL enabled first)
 *** - GCLK4 provides DFLL to SERCOM0 (this requires DFLL enabled first)
 *** This lines are to be copied into a function.
 ***/

#define GCLK_ADC          16
#define GCLK_TC0          14
#define GCLK_SERCOM0_CORE 11

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

/*** Enable GCLK3 with DFLL 
 *** as clock source 
 ***/
GCLK->GENCTRL[3].reg = GCLK_GENCTRL_DIV(1) | GCLK_GENCTRL_SRC_DFLLULP |GCLK_GENCTRL_GENEN|GCLK_GENCTRL_OE;
/*** (write synchronized) ***/
while((GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL3));
GCLK->PCHCTRL[GCLK_ADC].reg = (GCLK_PCHCTRL_CHEN|GCLK_PCHCTRL_GEN_GCLK3);

/*** Enable GCLK4 with DFLL 
 *** as clock source for SERCOM SPI 
 *** and TC4  
 ***/
GCLK->GENCTRL[4].reg = GCLK_GENCTRL_DIV(PWM_HIGH_GCLK_RATIO) | GCLK_GENCTRL_SRC_DFLLULP |GCLK_GENCTRL_GENEN|GCLK_GENCTRL_OE;
while((GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL4));
GCLK->PCHCTRL[GCLK_SERCOM0_CORE].reg = (GCLK_PCHCTRL_CHEN|GCLK_PCHCTRL_GEN_GCLK4);