10 Appendix

Configure OSCHF to Run at 1 MHz and Activate/Deactivate the Auto-Tune Feature

#define F_CPU                                   1000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#define DELAY_TIME                              1000
#define PRESSED                                 1
#define NOT_PRESSED                             0
#define PULL_UP_ENABLE                          0x08
#define BUTTON_PIN                              PIN7_bm

void CLK_init(void);
void PORT_init(void);

uint8_t volatile button_event = NOT_PRESSED;

int main(void)
{
    cli();
    PORT_init();
    CLK_init();
    sei();

    while (1) 
    {
        if(button_event == PRESSED) 
        {
            cli();
            _PROTECTED_WRITE (CLKCTRL.OSCHFCTRLA,(CLKCTRL_FREQSEL_1M_gc|CLKCTRL_AUTOTUNE_bm));
            _delay_ms(DELAY_TIME);
            _PROTECTED_WRITE (CLKCTRL.OSCHFCTRLA, CLKCTRL_FREQSEL_1M_gc);
            button_event = NOT_PRESSED;
            sei();
        }
    }
}

void CLK_init(void)
{
    _PROTECTED_WRITE (CLKCTRL.OSCHFCTRLA, CLKCTRL_FREQSEL_1M_gc);
    _PROTECTED_WRITE (CLKCTRL.XOSC32KCTRLA, CLKCTRL_ENABLE_bm);
    _PROTECTED_WRITE (CLKCTRL.MCLKCTRLA, (CLKCTRL_CLKSEL_OSCHF_gc | CLKCTRL_CLKOUT_bm)); 
}

void PORT_init(void)
{
    PORTC.DIRCLR = BUTTON_PIN;
    PORTC.INTFLAGS = BUTTON_PIN;
    PORTC.PIN7CTRL = PORT_ISC_RISING_gc | PULL_UP_ENABLE;
}

ISR(PORTC_PORT_vect)
{
    button_event = PRESSED;
    PORTC.INTFLAGS = BUTTON_PIN;
}