#include "hdl_spi4.h"

void hdl_spi4_init(void)
{
	stc_spi_init_t stcSpiInit;
    stc_gpio_init_t stcGpioInit;
	
	LL_PERIPH_WE(LL_PERIPH_GPIO | LL_PERIPH_EFM | LL_PERIPH_FCG | LL_PERIPH_PWC_CLK_RMU | LL_PERIPH_SRAM);

	/* 配置SPI引脚 */
	(void)GPIO_StructInit(&stcGpioInit);
    stcGpioInit.u16PinDrv = PIN_HIGH_DRV;

    stcGpioInit.u16PinDrv       = PIN_HIGH_DRV;
 
    (void)GPIO_Init(SPI4_SCLK_PORT, SPI4_SCLK_PIN, &stcGpioInit);
    (void)GPIO_Init(SPI4_MOSI_PORT, SPI4_MOSI_PIN, &stcGpioInit);
    (void)GPIO_Init(SPI4_MISO_PORT, SPI4_MISO_PIN, &stcGpioInit);

	GPIO_SetFunc(SPI4_SCLK_PORT,    SPI4_SCLK_PIN, SPI4_SCLK_FUNC);
    GPIO_SetFunc(SPI4_MOSI_PORT,    SPI4_MOSI_PIN, SPI4_MOSI_FUNC);
    GPIO_SetFunc(SPI4_MISO_PORT,    SPI4_MISO_PIN, SPI4_MISO_FUNC);
	
	/* 配置SPI参数 */
	SPI_StructInit(&stcSpiInit);

    FCG_Fcg1PeriphClockCmd(SPI4_CLOCK, ENABLE);
    
    stcSpiInit.u32WireMode          = SPI_3_WIRE;			//3线SPI
    stcSpiInit.u32TransMode         = SPI_FULL_DUPLEX;		//全双工
    stcSpiInit.u32MasterSlave       = SPI_MASTER;			//主机
	stcSpiInit.u32ModeFaultDetect   = SPI_MD_FAULT_DETECT_DISABLE;	// 禁用模式故障检测
    stcSpiInit.u32Parity            = SPI_PARITY_INVD;		//无奇偶校验
    stcSpiInit.u32SpiMode           = SPI_MD_3;				//SPI模式3
    stcSpiInit.u32BaudRatePrescaler = SPI_BR_CLK_DIV64;	//预分频
    stcSpiInit.u32DataBits          = SPI_DATA_SIZE_8BIT;	//数据宽度
    stcSpiInit.u32FirstBit          = SPI_FIRST_MSB;		//MSB高位有效	
    (void)SPI_Init(SPI4_INSTANCE, &stcSpiInit);
    SPI_Cmd(SPI4_INSTANCE, ENABLE);
	
	LL_PERIPH_WP(LL_PERIPH_EFM | LL_PERIPH_FCG | LL_PERIPH_SRAM);
	
}

uint8_t hdl_spi4_txrx(uint8_t w_data)
{
	uint8_t r_data = 0;
	uint16_t retry = 0;
	
	while (RESET == SPI_GetStatus(SPI4_INSTANCE, SPI_FLAG_TX_BUF_EMPTY))
	{
		retry++;
		if(retry > 200)
		{
			return 0;
		}
	}
    SPI_WriteData(SPI4_INSTANCE, (uint32_t)w_data);
	
    while (RESET == SPI_GetStatus(SPI4_INSTANCE, SPI_FLAG_RX_BUF_FULL))
	{
		retry++;
		if(retry > 200)
		{
			return 0;
		}
	}
    r_data = SPI_ReadData(SPI4_INSTANCE);
		
    return r_data;
}
