我做SPI通讯,用STM32做从机,把主机发过来的数据返回给主机,但是数据一直不正确,不是0xff就是0x00。
以下是我的从机配置,各位前辈帮忙分析下呗,这是我第一次接触STM32的,困难重重啊。
void SPI1_conf(void)
{
SPI_InitTypeDef SPI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
SPI_Cmd(SPI2, DISABLE);
//从模式
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//SPI_Direction_1Line_Rx;//
SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
//SPI_InitStructure.SPI_NSS = SPI_NSS_Hard;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = SPI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//SPI_Cmd(SPI1, ENABLE);
SPI_I2S_ITConfig(SPI1, SPI_I2S_IT_RXNE, ENABLE);
//SPI_I2S_ClearITPendingBit(SPI1, SPI_I2S_IT_RXNE);
//SPI2_ReadWriteByte(0xff);//启动传输
}
void SPI_GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_SPI1, ENABLE); //GPIOA/SPI1 时钟使能
//从模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5|GPIO_Pin_7; //sck mosi
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//miso
//GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7);
}
main里面在while做了如下操作
SPI_Cmd(SPI1, ENABLE);
if((SPI_ReadByte())!= 0)
{
SPI_SendByte(SPI1->DR);
}
SPI_Cmd(SPI1, DISABLE);
/******************************************/读
uc8 SPI_ReadByte(void)
{
while((SPI1->SR & SPI_I2S_FLAG_TXE)==(uc16)RESET);
SPI1->DR = 0xFF;
while((SPI1->SR & SPI_I2S_FLAG_RXNE)==(uc16)RESET);
return SPI1->DR;
}
/******************************************/发
u8 SPI_SendByte(u8 byte)
{
/* Loop while DR register in not emplty */
while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
/* Send byte through the SPI2 peripheral */
SPI_I2S_SendData(SPI1, byte);
/* Wait to receive a byte */
while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
/* Return the byte read from the SPI bus */
return SPI_I2S_ReceiveData(SPI1);
}
以上是我代码里关于SPI的所有操作了,求前辈帮忙分析分析是不是哪里不对了。
|