spi操作一定要注意spi的gpio的操作,开始因为spi_nss引脚设置成了复用推挽输出,浪费了很多时间。下面是正确的spi初始化和读写函数,在战舰开发板源码基础修改的。
void SPI1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE );
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; //SPI CS
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_4);
GPIO_SetBits(GPIOA,GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7);
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_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
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 = 7;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Cmd(SPI1, ENABLE); //ʹÄÜSPIÍâÉè
SPI1_ReadWriteByte(0xff);//Æô¶¯´«Êä
}
//SPI ËÙ¶ÈÉèÖú¯Êý
//SpeedSet:
//SPI_BaudRatePrescaler_2 2·ÖƵ
//SPI_BaudRatePrescaler_8 8·ÖƵ
//SPI_BaudRatePrescaler_16 16·ÖƵ
//SPI_BaudRatePrescaler_256 256·ÖƵ
void SPI1_SetSpeed(u8 SpeedSet)
{
SPI1->CR1&=0XFFC7;
SPI1->CR1|=SpeedSet;
SPI_Cmd(SPI1,ENABLE);
}
u8 SPI1_ReadWriteByte(u8 TxData)
{
u8 retry=0;
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET) //¼ì²éÖ¸¶¨µÄSPI±ê־λÉèÖÃÓë·ñ:·¢ËÍ»º´æ¿Õ±ê־λ
{
retry++;
if(retry>200)return 0;
}
SPI_I2S_SendData(SPI1, TxData); //ͨ¹ýÍâÉèSPIx·¢ËÍÒ»¸öÊý¾Ý
retry=0;
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET) //¼ì²éÖ¸¶¨µÄSPI±ê־λÉèÖÃÓë·ñ:½ÓÊÜ»º´æ·Ç¿Õ±ê־λ
{
retry++;
if(retry>200)return 0;
}
return SPI_I2S_ReceiveData(SPI1); //·µ»Øͨ¹ýSPIx×î½ü½ÓÊÕµÄÊý¾Ý
}