/**
  ************************************* Copyright ****************************** 
  *
  *                 Copyright (C), 2012-2016, Radioway Tech. Co., Ltd.
  *                            All Rights Reserved
  *
  *    
  * FileName   : spi.c
  * Version    : v1.0
  * Author     : Heb
  * Date       : 2024-06-27
  * Description: 
  * Function List: 
  	1. ....
          <version>: 
     <modify staff>: 
             <data>: 
      <description>: 
  	2. ...
  ******************************************************************************
 */

#include "board.h"

void spi_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    SPI_InitTypeDef  SPI_InitStruct;

    // 使能GPIO、SPI时钟
    RCC_APB1PeriphClockCmd(RCC_APB1ENR_SPI2, ENABLE);
    RCC_AHBPeriphClockCmd(RCC_AHBENR_GPIOB, ENABLE);
    
    // 初始化SPI1
    SPI_StructInit(&SPI_InitStruct);
    SPI_InitStruct.SPI_Mode      = SPI_Mode_Master;
    SPI_InitStruct.SPI_DataSize  = SPI_DataSize_8b;
    SPI_InitStruct.SPI_DataWidth = 8;
    SPI_InitStruct.SPI_CPOL      = SPI_CPOL_Low;
    SPI_InitStruct.SPI_CPHA      = SPI_CPHA_1Edge;
    SPI_InitStruct.SPI_NSS       = SPI_NSS_Soft;
    SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
    SPI_InitStruct.SPI_FirstBit  = SPI_FirstBit_MSB;
    SPI_Init(SPI2, &SPI_InitStruct);

    SPI_BiDirectionalLineConfig(SPI2, SPI_Direction_Rx);
    SPI_BiDirectionalLineConfig(SPI2, SPI_Direction_Tx);

    // 初始化GPIO
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource13,  GPIO_AF_0);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource14,  GPIO_AF_1);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource15,  GPIO_AF_3);

//    GPIO_StructInit(&GPIO_InitStruct);
//    GPIO_InitStruct.GPIO_Pin   =  GPIO_Pin_12;
//    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
//    GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_Out_PP;
//    GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin   =  GPIO_Pin_13 | GPIO_Pin_14;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin   = GPIO_Pin_15;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_IPU;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    SPI_Cmd(SPI2, ENABLE);
}

uint8_t spi_inout(uint8_t out_data)
{
    uint16_t time_out = 0;
    uint32_t in_data = 0;
    
    while (RESET == SPI_GetFlagStatus(SPI2, SPI_FLAG_TXEPT))
    {
        time_out++;
        if(time_out > 251)
            return 0;
    }
    time_out = 0;
    SPI_SendData(SPI2, out_data);
    while (RESET == SPI_GetFlagStatus(SPI2, SPI_FLAG_RXAVL))
    {
        time_out++;
        if(time_out > 251)
            return 0;
    }

    in_data = SPI_ReceiveData(SPI2);
    
    return (uint8_t)in_data;
}


