/**************************************************************************//**
 * @file     pan_spi.c
 * @version  V1.10
 * $Revision: 2 $
 * $Date:    19/10/22  17:18 $
 * @brief    PAN series SPI driver source file
 *
 * @note
 * Copyright (C) 2025 Panchip Technology Corp. All rights reserved.
*****************************************************************************/
#include "pan271x.h"
#include "pan_spi.h"

/** @addtogroup PAN_Device_Driver PAN Device Driver
  @{
*/

/** @addtogroup PAN_SPI_Driver SPI Driver
  @{
*/

/** @addtogroup PAN_SPI_EXPORTED_FUNCTIONS SPI Exported Functions
  @{
*/

/**
  * @brief  Initializes the SPIx peripheral according to the specified
  *         parameters in the SPI_InitStruct .
  * @param  SPIx: where x can be 1, 2 to select the
  *         SPI peripheral.
  * @param  SPI_InitStruct: pointer to a SPI_InitTypeDef structure that contains
  *         the configuration information for the specified SPI peripheral.
  * @retval None
  */
uint32_t SPI_Init(SPI_T* SPIx, SPI_InitTypeDef* SPI_InitStruct)
{
    uint32_t tmpreg = 0;
	uint32_t apbClk = CLK_GetPeripheralFreq((void*)SPIx);

    if(SPI_IsSpiEnabled(SPIx))
        SPI_DisableSpi(SPIx);

    tmpreg = SPIx->SSPCR0;

    tmpreg &= ~(SSPCR0_SPH_Msk | SSPCR0_SPO_Msk  | SSPCR0_DSS_Msk);
    tmpreg |= (
               ((SPI_InitStruct->SPI_CPHA           << SSPCR0_SPH_Pos) & SSPCR0_SPH_Msk )  |   \
                ((SPI_InitStruct->SPI_CPOL          << SSPCR0_SPO_Pos) & SSPCR0_SPO_Msk )  |   \
                ((SPI_InitStruct->SPI_dataFrameSize << SSPCR0_DSS_Pos) & SSPCR0_DSS_Msk )      \
              );
    tmpreg &= ~(SSPCR0_SCR_Msk);
    tmpreg |= ((SPI_InitStruct->SPI_baudRateDiv-1) << SSPCR0_SCR_Pos);   //Fixed SCR to 0, only use SSPCPSR to config baudrate

    SPIx->SSPCR0 = tmpreg;

    //Baudrate Config, expect_baudrate = apb_clk / ((1 + SCR) * SSPCPSR)
    SPIx->SSPCPSR = 2;//SPI_InitStruct->SPI_baudRateDiv;

    //Role Select
    if(SPI_InitStruct->SPI_role == SPI_RoleSlave)
    {
        SPIx->SSPCR1 |= SSPCR1_MS_Msk;
    }
    else
    {
        SPIx->SSPCR1 &= ~SSPCR1_MS_Msk;
    }
	
	return apbClk / (SPI_InitStruct->SPI_baudRateDiv * SPIx->SSPCPSR);
}


/*@}*/ /* end of group PAN_SPI_EXPORTED_FUNCTIONS */

/*@}*/ /* end of group PAN_SPI_Driver */

/*@}*/ /* end of group PAN_Device_Driver */

/*** (C) COPYRIGHT 2016 Panchip Technology Corp. ***/
