#include <avr/io.h>
#include <util/delay.h>
#include "uart.h"
#include <avr/interrupt.h>

void init_clk(void)
{

    // ========= System Clock configuration =========
    // Set to external 16Mhz crystal, using the PLL at *2
    // set it to be a 12-16Mhz crystal with a slow start-up time.
    OSC.XOSCCTRL = OSC_FRQRANGE_2TO9_gc | OSC_XOSCSEL_XTAL_16KCLK_gc ;
    OSC.CTRL |= OSC_XOSCEN_bm ; // enable it
    while( (OSC.STATUS & OSC_XOSCRDY_bm) == 0 ){} // wait until it's stable

    // The external crystal is now running and stable.
    // (Note that it's not yet selected as the clock source)
    // Now configure the PLL to be eXternal oscillator * 2
    OSC.PLLCTRL = OSC_PLLSRC_XOSC_gc | 2;

    // now enable the PLL...
    OSC.CTRL |= OSC_PLLEN_bm ; // enable the PLL...
    while( (OSC.STATUS & OSC_PLLRDY_bm) == 0 ){} // wait until it's stable

    // And now, *finally*, we can switch from the internal 2Mhz clock to the PLL
    CCP = CCP_IOREG_gc;	// protected write follows   
    CLK.CTRL = CLK_SCLKSEL_PLL_gc;	// The System clock is now  PLL (16Mhz * 2)
    // ==============================================
}

int main(void){
    init_clk();
    init_uart();
    PORTD.DIRSET = 1 << 5;
    sei();
    
    for(;;){
        char tmp = USARTD0.DATA;
        if(!tmp)
            tmp='a';
        USARTD0.DATA = tmp;
        PORTD.OUTTGL = 1 << 5;
        _delay_ms(1000);
    }
}
