我想使用SPI通讯2个STM32板。我将一块板用作主板,另一块板作为从板。
我可以使用HAL_SPI_Transmit()和HAL_SPI_Receive()函数进行发送和接收。现在,我想将slave配置为以中断模式接收,但是此中断永远不会触发。
这是我在两块板上都使用的代码:
大师
int main(void)
{
uint8_t txdata [] = {0x01, 0x02, 0x03, 0x04};
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_SPI2_Init();
while (1)
{
HAL_SPI_Transmit(&hspi2, txdata, 4, 20);
HAL_Delay(2000);
}
}
static void MX_SPI2_Init(void)
{
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_LOW;
hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi2.Init.NSS = SPI_NSS_SOFT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 7;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
}
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hspi->Instance==SPI2)
{
__HAL_RCC_SPI2_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_15|GPIO_PIN_14|GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF0_SPI2;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
}
奴隶
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_SPI2_Init();
HAL_SPI_Receive_IT(&hspi2, rxdata, 4);
while (1)
{
}
}
void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
if (hspi->Instance == SPI2)
{
printf("%d", rxdata[0]);
printf("%d", rxdata[1]);
printf("%d", rxdata[2]);
printf("%d", rxdata[3]);
printf("\r\n");
rxdata[0] = 0;
rxdata[1] = 0;
rxdata[2] = 0;
rxdata[3] = 0;
HAL_SPI_Receive_IT(&hspi2, rxdata, 4);
}
}
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hspi->Instance==SPI2)
{
__HAL_RCC_SPI2_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_15|GPIO_PIN_14|GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF0_SPI2;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
HAL_NVIC_SetPriority(SPI2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(SPI2_IRQn);
}
}
void SPI2_IRQHandler(void)
{
HAL_SPI_IRQHandler(&hspi2);
}
答案 0 :(得分:0)
结果表明,在主设备和从设备中BaudPreescaler都设置为SPI_BAUDRATEPRESCALER_2,但是由于某些原因,此变量在每个项目中都有不同的值。
这使通讯无法正常工作并收到噪音。