#include <samd21g18a.h>
#include "SPI.h"

/* initialize SPI on SERCOM0 with MOSI on pad 0 (pin PA08) */
void SPI_init(void)
{
	/* enable peripheral clock */
	PM->APBCMASK.bit.SERCOM0_ = 1;
	
	/* enable generic clock */
	GCLK->CLKCTRL.bit.ID = GCLK_CLKCTRL_ID_SERCOM0_CORE_Val;     // configure generic clock for SERCOM0
	GCLK->CLKCTRL.bit.GEN = GCLK_CLKCTRL_GEN_GCLK0_Val;          // source is generic clock generator 0 
	GCLK->CLKCTRL.bit.CLKEN = 1;                                 // enable generic clock
	
	/* select GPIO pins alternative function */
	PORT->Group[0].PINCFG[8].bit.PMUXEN = 1;                     // enable alternative function for pin PA08
	PORT->Group[0].PMUX[4].bit.PMUXE = MUX_PA08C_SERCOM0_PAD0;   // PA08 alternative function C (SERCOM0 pad 0)
	
	/* configure peripheral */
	SERCOM0->SPI.CTRLA.bit.DOPO = 0x00;                          // MOSI on pad 0 (pin PA08)
	SERCOM0->SPI.CTRLA.bit.CPHA = 0x00;  
	SERCOM0->SPI.CTRLA.bit.CPOL = 0x00;                          // transfer mode 0
	SERCOM0->SPI.CTRLA.bit.DORD = 0x00;                          // MSB first
	SERCOM0->SPI.CTRLA.bit.MODE = 0x03;                          // SPI master operation
	SERCOM0->SPI.CTRLB.bit.CHSIZE = 0x00;                        // 8 bit character size
	SERCOM0->SPI.BAUD.reg = 9;                                   // SPI frequency 2.4 MHz (BAUD = gclk/(2*f_baud) - 1)
	
	/* enable peripheral */
	SERCOM0->SPI.CTRLA.reg |= SERCOM_SPI_CTRLA_ENABLE;
}

