STM32CubeMx配置SPI注意的一個問題
這樣配置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;
}
這才成功!