/********************************************************************************
 * @file    SPI_Master.c
 * @author  SOC AE Team
 * @version V1.1
 * @date    24-07-2023
 * @brief
 *
 *******************************************************************************/
#include "sc32_conf.h"
#include "Function_Init.h"

static volatile FlagStatus SPI_Flag = RESET;

void SPI_Master_Function(void)
{
	volatile uint8_t SPI_RxData;
	SPI_InitTypeDef SPI_InitStruct; //定义SPI初始化结构体变量

	/* 使能SPI0和SPI0的时钟 */
  RCC_APB0Cmd(ENABLE);  //SPI0和1外设挂载在APB0时钟上
	RCC_APB0PeriphClockCmd(RCC_APB0Periph_SPI0,ENABLE);

	SPI_InitStruct.SPI_CPHA = SPI_CPHA_1Edge;	//SPI第一沿采集数据
	SPI_InitStruct.SPI_CPOL = SPI_CPOL_Low;	//SPI空闲电平为低电平
	SPI_InitStruct.SPI_DataSize = SPI_DataSize_8B;	//数据长度为8位
	SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;	//数值传输为高位在前
	SPI_InitStruct.SPI_Mode = SPI_Mode_Master;	//SPI工作在主机模式
	SPI_InitStruct.SPI_Prescaler = SPI_Prescaler_1024;	//SPI传输频率为APB0时钟1分频
	
	/*  根据结构体配置初始化串口 */
	SPI_Init(SPI0,&SPI_InitStruct);		
	
	/* 使能串口接收中断 */
	SPI_ITConfig(SPI0,SPI_IT_INTEN,ENABLE);
	NVIC_EnableIRQ(SPI0_IRQn);

	/* 使能接收发送口 */
	SPI_Cmd(SPI0,ENABLE);

	while(1)
	{
		SPI_SendData(SPI0,0x5A);
		printf("SPI0 发送0x5A！\r\n");
		while(SPI_Flag == RESET);
		SPI_RxData = SPI_ReceiveData(SPI0);
		SPI_Flag = SET;
		printf("SPI0 接收到的数据为：0x%x\r\n",SPI_RxData);
	}
}

void SPI_Master_SPI0Handler(void)
{
	if(SPI_GetFlagStatus(SPI0,SPI_Flag_SPIF))
	{
		SPI_ClearFlag(SPI0,SPI_Flag_SPIF);
		SPI_Flag = SET;
	}
}
