/*
 * Copyright  2017 NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "fsl_spi.h"
#include "spi_to_dual_usart_bridge.h"

/*******************************************************************************
 * Variables
 ******************************************************************************/

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * brief  SPI send data 
 * param  uint8_t data->data to be sent
 * return void
 */
void BOARD_SPISendData(uint8_t data)
{
	SPI_WriteData(SPI0,data);
}

/*!
 * brief  SPI interrupt service routine
 * param  void
 * return void
 */
void SPI0_IRQHandler(void)
{	
	//a buffer that holds temporary data
	uint8_t tempSPIData = 0;
	
	if(SPI_GetStatusFlags(SPI0) & kSPI_RxReadyFlag)
	{//SPI has received data from SPI host
		//read data from SPI host
		tempSPIData = SPI_ReadData(SPI0);
		//preprocess data from SPI host
		preprocessDataFromSPIHost(tempSPIData);
	}
	if(SPI_GetStatusFlags(SPI0) & kSPI_TxReadyFlag)
	{//SPI is ready to send data in rx fifo to SPI host
		//send data in rx fifo to SPI host
		sendDataFromUSARTToSPIHost();
	}
	__DSB();
}

/*!
 * brief  SPI slave initialization
 * param  void
 * return void
 */
void BOARD_SPISlaveInit(void)
{
	//SPI slave configuration structure
	spi_slave_config_t slaveConfig = {0};

	//get the default configuration of SPI slave
	SPI_SlaveGetDefaultConfig(&slaveConfig);
	//initialize the SPI slave with configuration above
	SPI_SlaveInit(SPI0, &slaveConfig);

	//enable SPI interrupt in NVIC
	EnableIRQ(SPI0_IRQn);
	//enable RX ready interrupt in SPI
	SPI_EnableInterrupts(SPI0, kSPI_RxReadyInterruptEnable);
}

