5 XOSCHF with External Clock

To use XOSCHF with an external clock signal, the SELHF bit and the ENABLE bit in the External High-Frequency Oscillator Control A (CLKCTRL.XOSCHFCTRLA) register must be written to ‘1’.

This register has Configuration Change Protection (CCP), so the ccp_write_io function in cpufunc.h should be used to ensure correct timing for the unlock of the register.

Figure 5-1. CLKCTRL.XOSCHFCTRLA – Enable XOSCHF

	/* Enable external clock input */
	ccp_write_io((uint8_t *) &CLKCTRL.XOSCHFCTRLA, 
	             CLKCTRL_SELHF_EXTCLOCK_gc | CLKCTRL_ENABLE_bm);

If changing Main Clock to use XOSCHF as the clock source, first make sure to set the Main Clock prescaler to output maximum 24 MHz by writing a prescaler setting to the Prescaler Division (PDIV) bit field and ‘1’ to the Prescaler Enable (PEN) bit in the Main Clock Control B (CLKCTRL.MCLKCTRLB) register. This register also has CCP.

Figure 5-3. CLKCTRL.MCLKCTRLB – Configure Main Clock prescaler

	/* Set Main Clock Prescaler */
	ccp_write_io((uint8_t *) &CLKCTRL.MCLKCTRLB, 
	             CLKCTRL_PDIV_2X_gc | CLKCTRL_PEN_bm);

Change Main Clock source by writing the EXTCLK setting to the Clock Select (CLKSEL) bit field in the Main Clock Control A (CLKCTRL.MCLKCTRLA) register. The Main Clock Out (CLKOUT) bit can be written to ‘1’ to output the Main Clock on the CLKOUT pin. This register also has CCP.

Figure 5-4. CLKCTRL.MCLKCTRLA – Change source to XOSCHF

	/* Set the main clock to use XOSCHF as source, and enable the CLKOUT pin */
	ccp_write_io((uint8_t *) &CLKCTRL.MCLKCTRLA, 
	             CLKCTRL_CLKSEL_EXTCLK_gc | CLKCTRL_CLKOUT_bm);

After changing the Main Clock source, wait for the switch to complete by polling the Main Clock Oscillator Changing (SOSC) bit in the Main Clock Status (CLKCTRL.MCLKSTATUS) register until the bit is read as ‘0’.

Figure 5-5. CLKCTRL.MCLKSTATUS – Wait for Main Clock to change

	/* Wait for system oscillator changing to complete */
	while(CLKCTRL.MCLKSTATUS & CLKCTRL_SOSC_bm)
	{
		;
	}

The code for this example is available in the XOSCHF-with-external-clock folder in these github repositories: