#include "spi.h"
#include "usart.h"

u8 spi1_buffer[8192];
u16 spi1_renum=0;

//SPI1初始化
void SPI1_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;                              //相关结构体定义 GPIO 
  SPI_InitTypeDef  SPI_InitStructure;                                //相关结构体定义 SPI
	NVIC_InitTypeDef NVIC_InitStructure;	                             //相关结构体定义 中断	
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);              //使能 GPIOB 时钟
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);	             //使能SPI1时钟	
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5;    //PB3-5复用功能输出	
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;                       //复用功能
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;                     //推挽输出
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;                 //100MHz
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;                       //上拉
  GPIO_Init(GPIOB, &GPIO_InitStructure);                             //初始化	GPIOB
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource3,GPIO_AF_SPI1);              //GPIOB-3 复用为SPI1
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource4,GPIO_AF_SPI1);              //GPIOB-4 复用为SPI1
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource5,GPIO_AF_SPI1);              //GPIOB-5 复用为SPI1
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //设置SPI单向或者双向的数据模式:SPI设置为双线双向全双工
	SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;		                   //设置SPI工作模式:设置为从SPI
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;		               //设置SPI的数据大小:SPI发送接收8位帧结构
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;		                     //串行同步时钟的空闲状态为高电平
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;	                     //串行同步时钟的第二个跳变沿（上升或下降）数据被采样
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;	                         //NSS信号由软件管理:内部NSS信号有SSI位控制
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; //定义波特率预分频的值:波特率预分频值为256
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;	               //指定数据传输从MSB位还是LSB位开始:数据传输从MSB位开始
	SPI_InitStructure.SPI_CRCPolynomial = 7;	                         //CRC值计算的多项式
	SPI_Init(SPI1, &SPI_InitStructure);                                //根据SPI_InitStruct中指定的参数初始化外设SPIx寄存器
	SPI_Cmd(SPI1, ENABLE);                                             //使能SPI外设 
	SPI_I2S_ITConfig(SPI1, SPI_I2S_IT_RXNE, ENABLE);                   //开启相关中断
  NVIC_InitStructure.NVIC_IRQChannel = SPI1_IRQn;                    //串口1中断通道
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;            //抢占优先级3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority =2;		               //子优先级3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			               //IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	                                   //根据指定的参数初始化NVIC寄存器
}

//SPI1中断函数
void SPI1_IRQHandler(void)
{
	if((SPI1->SR%2==1))
	{
		spi1_buffer[spi1_renum]=SPI1->DR;
		spi1_renum++;
		if(spi1_renum>=8192)
			spi1_renum=0;
	}
}
