#include <atmel_start.h>

#define MASTER_BUFFER_SIZE	32
static uint8_t rx_buffer[MASTER_BUFFER_SIZE] = {};
static uint8_t tx_buffer[MASTER_BUFFER_SIZE] =  {31,30,29,28,27,26,25,24,23,22,
												21,20,19,18,17,16,15,14,13,12,
												11,10,9,8,7,6,5,4,3,2,1,0};
												
static struct timer_task TIMER_0_task1;	
/**
 * Example of using TIMER_0.
 */
static void timer_task_cb(const struct timer_task *const timer_task)
{
	gpio_set_pin_level(SPI_CS, false);
	tx_buffer[MASTER_BUFFER_SIZE-1] = tx_buffer[MASTER_BUFFER_SIZE-1] + 1;
	spi_m_dma_transfer(&SPI_0, tx_buffer, rx_buffer, MASTER_BUFFER_SIZE);
	volatile int i = 0;
}

static void	b2bTransferComplete_cb(struct _dma_resource *resource)
{
	delay_us(10);	
	gpio_set_pin_level(SPI_CS, true);
	/* Transfer completed */
	//printf("Sent: ");
	//print_buffer(tx_buffer, MASTER_BUFFER_SIZE);
	//printf("Received: ");
	//print_buffer(rx_buffer, MASTER_BUFFER_SIZE);
	timer_start(&TIMER_0);
}

void timerTaskInit(void)
{
	TIMER_0_task1.interval = 1000;
	TIMER_0_task1.cb       = timer_task_cb;
	TIMER_0_task1.mode     = TIMER_TASK_REPEAT;
	
	timer_add_task(&TIMER_0, &TIMER_0_task1);
	timer_start(&TIMER_0);
}

void boardToBoardTransferInit(void)
{
	struct io_descriptor *io;
	spi_m_dma_get_io_descriptor(&SPI_0, &io);
	spi_m_dma_register_callback(&SPI_0, SPI_M_DMA_CB_RX_DONE, b2bTransferComplete_cb);
	//SERCOM4->SPI.CTRLC.bit.DATA32B = true;
	spi_m_dma_enable(&SPI_0);
}
void print_buffer( uint8_t *buffer, uint16_t length)
{
	/* Print Received data by SPI Master from SPI Slave on Console */
	for (int i = 0; i < length; i++) {
		printf("%u, ", rx_buffer[i]);
	}
	printf("\n\r");
}

int main(void)
{
	/* Initializes MCU, drivers and middleware */
	atmel_start_init();
	timerTaskInit();
	boardToBoardTransferInit();
	gpio_set_pin_level(SPI_CS, true);
	printf("Init Complete\n\r");
	
	gpio_set_pin_level(SPI_CS, false);
	spi_m_dma_transfer(&SPI_0, tx_buffer, rx_buffer, MASTER_BUFFER_SIZE);

	/* Replace with your application code */
	while (1) {
	}
}
