这样配置SPI引脚
然后这样配置SPI参数
生成立这样的配置代码
/* SPI2 init function */
static void MX_SPI2_Init(void)
{
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi2.Init.NSS = SPI_NSS_SOFT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_ENABLE;
hspi2.Init.CRCPolynomial = 14;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
然后它的SPI引脚是这样的代码
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hspi->Instance==SPI2)
{
/* USER CODE BEGIN SPI2_MspInit 0 */
/* USER CODE END SPI2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SPI2_CLK_ENABLE();
/**SPI2 GPIO Configuration
PB12 ------> SPI2_NSS
PB13 ------> SPI2_SCK
PB14 ------> SPI2_MISO
PB15 ------> SPI2_MOSI
*/
GPIO_InitStruct.Pin = Z_CSN_Pin|Z_SCK_Pin|Z_SDI_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = Z_SDO_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(Z_SDO_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN SPI2_MspInit 1 */
/* USER CODE END SPI2_MspInit 1 */
}
}
注意Z_CSN_Pin配置成了AF模式。
所以收发函数想要这样用:
uint8_t d_read,d_send;
HAL_SPI_TransmitReceive(&hspi2,&d_send,&d_read,1,0xFFF);
结果是:这个收发语句执行了,但用示波器看Z_CSN_Pin并没有在执行过程中自动拉低!自然是不能收发成功的。
hspi2.Init.NSS = SPI_NSS_SOFT;这个语句的含义并不是NSS软件自动控制?!
不得已,只好在初始化后重新定义Z_CSN_Pin:
void MX_SPI2_Init_IO_ReDefine(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/**SPI GPIO Configuration
*/
GPIO_InitStruct.Pin = Z_CSN_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
然后收发时加上Z_CSN_Pin拉低和拉高!
/**
* 函数功能: 从SPI发送4个字节数据
* 输入参数: 无
* 返 回 值: uint32_t:读取到的数据
* 说 明:This function must be used only if the Start_Read_Sequence
* function has been previously called.
*/
uint32_t M1_SPI0SndByte(uint32_t data)
{
uint32_t x=0;
uint8_t d_read[4],d_send[3]={0};
HAL_GPIO_WritePin (GPIOB, Z_CSN_Pin, GPIO_PIN_RESET);
// HAL_Delay(1);
d_send[0]=(data>>16)&0xff;
d_send[1]=(data>>8)&0xff;
d_send[2]=(data)&0xff;
if(HAL_SPI_TransmitReceive(&hspi2,d_send,d_read,3,0xFFF)!=HAL_OK)
x=0xffffffff;
HAL_GPIO_WritePin (GPIOB, Z_CSN_Pin, GPIO_PIN_SET);
// HAL_Delay(1);
return x;
}
这才成功!