- /* Enable and configure internal Fast RC oscillator */
- CKGR_MOR_R =
- CKGR_MOR_KEY(CKGR_KEY) // Unlock key
- | CKGR_MOR_MOSCRCEN // Main On-Chip RC oscillator enable
- | CKGR_MOR_MOSCRCF_12MHZ; // RC oscillator frequency
+ uint32_t timeout;
+
+ /* Disable watchdog */
+ WDT_MR = BV(WDT_WDDIS);
+
+ /* Set 4 wait states for flash access, needed for higher CPU clock rates */
+ EEFC_FMR = EEFC_FMR_FWS(3);
+
+ // Select external slow clock
+ if (!(SUPC_SR & BV(SUPC_SR_OSCSEL)))
+ {
+ SUPC_CR = BV(SUPC_CR_XTALSEL) | SUPC_CR_KEY(0xA5);
+ while (!(SUPC_SR & BV(SUPC_SR_OSCSEL)));
+ }
+
+ // Initialize main oscillator
+ if (!(CKGR_MOR & BV(CKGR_MOR_MOSCSEL)))
+ {
+ CKGR_MOR = CKGR_MOR_KEY(0x37) | BOARD_OSC_COUNT | BV(CKGR_MOR_MOSCRCEN) | BV(CKGR_MOR_MOSCXTEN);
+ timeout = CLOCK_TIMEOUT;
+ while (!(PMC_SR & BV(PMC_SR_MOSCXTS)) && --timeout);
+ }
+
+ // Switch to external oscillator
+ CKGR_MOR = CKGR_MOR_KEY(0x37) | BOARD_OSC_COUNT | BV(CKGR_MOR_MOSCRCEN) | BV(CKGR_MOR_MOSCXTEN) | BV(CKGR_MOR_MOSCSEL);
+ timeout = CLOCK_TIMEOUT;
+ while (!(PMC_SR & BV(PMC_SR_MOSCSELS)) && --timeout);
+
+ PMC_MCKR = (PMC_MCKR & ~(uint32_t)PMC_MCKR_CSS_MASK) | PMC_MCKR_CSS_MAIN_CLK;
+ timeout = CLOCK_TIMEOUT;
+ while (!(PMC_SR & BV(PMC_SR_MCKRDY)) && --timeout);
+
+ // Initialize and enable PLL clock
+ CKGR_PLLR = evaluate_pll() | BV(CKGR_PLLR_STUCKTO1) | CKGR_PLLR_PLLCOUNT(0x1);
+ timeout = CLOCK_TIMEOUT;
+ while (!(PMC_SR & BV(PMC_SR_LOCK)) && --timeout);