STM32 CANFD cubemx设置流程(基于MP157正点原子开发板)
AutoRetransmission 设置为enable 可以防止通讯速度过快时丢包
下图所示的TxBuffersNbr 和 TxFifoQueueElmtsNbr 貌似是共享32个地址的,两者加起来不能超过32
1.设置硬件参数(引脚,时钟)
1.1 启用FDCAN1,并设置参数
启用FDCAN后参数设置如下:
- 设置FDCAN引脚,手头板子tx rx分别为PH13 PI9
- 设置参数
- 其中elmets Size因为采用classicmode 所以选用8bytes,注意 buffers nbr MP157rx和tx最多有32个buffer,offset貌似不设置也没事,波特率算法可参考下方网站
https://www.cnblogs.com/Tuple-Joe/p/13278462.html
- 时钟设置
1.2启用FDCAN
首先可以设置过滤器,随后启动FDCAN
/*##-1 Configure the FDCAN filters ########################################*/
/* Configure standard ID reception filter to Rx FIFO 0 */
sFilterConfig.IdType = FDCAN_STANDARD_ID;
sFilterConfig.FilterIndex = 0;
sFilterConfig.FilterType = FDCAN_FILTER_MASK;
sFilterConfig.FilterConfig = FDCAN_FILTER_TO_RXFIFO0;
sFilterConfig.FilterID1 = 0x444;
sFilterConfig.FilterID2 = 0x555;
if (HAL_FDCAN_ConfigFilter(&hfdcan1, &sFilterConfig) != HAL_OK)
{
Error_Handler();
}
/* Configure extended ID reception filter to Rx FIFO 1 */
sFilterConfig.IdType = FDCAN_EXTENDED_ID;
sFilterConfig.FilterIndex = 0;
sFilterConfig.FilterType = FDCAN_FILTER_MASK;
sFilterConfig.FilterConfig = FDCAN_FILTER_TO_RXFIFO1;
sFilterConfig.FilterID1 = 0x1111111;
sFilterConfig.FilterID2 = 0x2222222;
if (HAL_FDCAN_ConfigFilter(&hfdcan1, &sFilterConfig) != HAL_OK)
{
Error_Handler();
}
/*##-2 Start FDCAN controller (continuous listening CAN bus) ##############*/
if (HAL_FDCAN_Start(&hfdcan1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE END 2 */
发送数据
/*##-3 Transmit messages ##################################################*/
/* Add message to Tx FIFO */
TxHeader.Identifier = 0x444;
TxHeader.IdType = FDCAN_STANDARD_ID;
TxHeader.TxFrameType = FDCAN_DATA_FRAME;
TxHeader.DataLength = FDCAN_DLC_BYTES_8;
TxHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE;
TxHeader.BitRateSwitch = FDCAN_BRS_ON;
TxHeader.FDFormat = FDCAN_FD_CAN;
TxHeader.TxEventFifoControl = FDCAN_STORE_TX_EVENTS;
TxHeader.MessageMarker = 0x52;
if (HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TxHeader, TxData0) != HAL_OK)
{
Error_Handler();
}
等待发送完成
/* Check transmission occurred before timeout */
while(HAL_FDCAN_IsTxBufferMessagePending(&hfdcan1, FDCAN_TX_BUFFER0 | FDCAN_TX_BUFFER1 | FDCAN_TX_BUFFER2) != 0)
{
if((HAL_GetTick() - Tickstart) > TX_FAST_TIMEOUT)
{
Error_Handler();
break;
}
}
查询接收到的can数据
while(HAL_FDCAN_GetRxFifoFillLevel(&hfdcan1, FDCAN_RX_FIFO0) != 1)
{
if((HAL_GetTick() - Tickstart) > RX_FAST_TIMEOUT)
{
Error_Handler();
break;
}
}
获取数据
if (HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_FIFO0, &RxHeader, RxData) != HAL_OK)
{
Error_Handler();
}