#include "user_spi.h"

/*******************************************************************************
  * @函数名称   SPI_FullDuplex_Init
  * @函数说明   SPI初始化
  * @输入参数  	无
  * @输出参数   无
  * @返回参数   无
*******************************************************************************/
void user_spi_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure = {0};
    SPI_InitTypeDef  SPI_InitStructure = {0};

    USER_NFC_SPI_RCC_ENABLE;

    GPIO_InitStructure.GPIO_Pin = USER_NFC_SCLK_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(USER_NFC_SCLK_GPIO, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = USER_NFC_MISO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(USER_NFC_MISO_GPIO, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = USER_NFC_MOSI_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(USER_NFC_MOSI_GPIO, &GPIO_InitStructure);

    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
    SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
    SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
    SPI_InitStructure.SPI_CRCPolynomial = 10;
    SPI_Init(USER_NFC_SPI, &SPI_InitStructure);

    SPI_Cmd(USER_NFC_SPI, ENABLE);
}

/*******************************************************************************
* Function Name  : SPI_ReadWriteByte
* Description    : SPI读写字节
* Input          : unsigned char TxData 写入字节
* Output         : None
* Return         : unsigned char RxData 读取字节
Flash_ReadWriteByte
*******************************************************************************/
uint8_t SPI_ReadWriteByte(uint8_t TxData)
{
    uint8_t timeout = 0;
    uint8_t RxData = 0;
    while(SPI_I2S_GetFlagStatus(USER_NFC_SPI, SPI_I2S_FLAG_TXE) == RESET)
    {
      timeout++;
      if(timeout > 200)
      {
        return 0;
      }
    }

    SPI_I2S_SendData(USER_NFC_SPI, TxData);
    timeout = 0;
    while(SPI_I2S_GetFlagStatus(USER_NFC_SPI, SPI_I2S_FLAG_RXNE) == RESET)
    {
      timeout++;
      if(timeout > 200)
      {
        return 0;
      }
    }

    RxData = SPI_I2S_ReceiveData(USER_NFC_SPI);
    return (uint8_t)RxData;
}
