在STM32中CAN1和CAN3是独立的,CAN2和CAN1有关联,所以在CAN2初始化和设置过滤器前需要添加CAN1的代码。
CAN_HandleTypeDef hcan1;
/* CAN1 init function */
void MX_CAN1_Init(void)
{
/* USER CODE BEGIN CAN1_Init 0 */
/* USER CODE END CAN1_Init 0 */
/* USER CODE BEGIN CAN1_Init 1 */
/* USER CODE END CAN1_Init 1 */
hcan1.Instance = CAN1;
hcan1.Init.Prescaler = 10;
hcan1.Init.Mode = CAN_MODE_NORMAL;
hcan1.Init.SyncJumpWidth = CAN_SJW_1TQ;
hcan1.Init.TimeSeg1 = CAN_BS1_7TQ;
hcan1.Init.TimeSeg2 = CAN_BS2_2TQ;
hcan1.Init.TimeTriggeredMode = ENABLE;
hcan1.Init.AutoBusOff = DISABLE;
hcan1.Init.AutoWakeUp = DISABLE;
hcan1.Init.AutoRetransmission = DISABLE;
hcan1.Init.ReceiveFifoLocked = DISABLE;
hcan1.Init.TransmitFifoPriority = DISABLE;
/*
if (HAL_CAN_Init(&hcan1) != HAL_OK)
{
Error_Handler();
}
*/
/* USER CODE BEGIN CAN1_Init 2 */
/* USER CODE END CAN1_Init 2 */
}
void CAN1_ConfigFilter(void)
{
CAN_FilterTypeDef CAN_FilterConfigStructure;
CAN_FilterConfigStructure.FilterBank = 0;
CAN_FilterConfigStructure.FilterMode = CAN_FILTERMODE_IDMASK;
CAN_FilterConfigStructure.FilterScale = CAN_FILTERSCALE_32BIT;
CAN_FilterConfigStructure.FilterIdHigh = 0x0000;
CAN_FilterConfigStructure.FilterIdLow = 0x0000;
CAN_FilterConfigStructure.FilterMaskIdHigh = 0x0000;
CAN_FilterConfigStructure.FilterMaskIdLow = 0x0000;
CAN_FilterConfigStructure.FilterFIFOAssignment = CAN_RX_FIFO0;
CAN_FilterConfigStructure.SlaveStartFilterBank = 14;
CAN_FilterConfigStructure.FilterActivation = ENABLE;
HAL_CAN_ConfigFilter(&hcan1, &CAN_FilterConfigStructure);
}
/*!
@Brief
Config the CAN filter
@Param
null
@Return
null
*/
void CAN2_ConfigFilter(void)
{
CAN_FilterTypeDef CAN_FilterConfigStructure;
CAN_FilterConfigStructure.FilterBank = 14;
CAN_FilterConfigStructure.FilterMode = CAN_FILTERMODE_IDMASK;
CAN_FilterConfigStructure.FilterScale = CAN_FILTERSCALE_32BIT;
CAN_FilterConfigStructure.FilterIdHigh = 0x0000;
CAN_FilterConfigStructure.FilterIdLow = 0x0000;
CAN_FilterConfigStructure.FilterMaskIdHigh = 0x0000;
CAN_FilterConfigStructure.FilterMaskIdLow = 0x0000;
CAN_FilterConfigStructure.FilterFIFOAssignment = CAN_RX_FIFO0;
CAN_FilterConfigStructure.SlaveStartFilterBank = 14;
CAN_FilterConfigStructure.FilterActivation = ENABLE;
HAL_CAN_ConfigFilter(&hcan2, &CAN_FilterConfigStructure);
}
主要的核心是需要对CAN1和CAN2的过滤器同时设置。
CAN1设置为 CAN_FilterConfigStructure.FilterBank = 0;
CAN2设置为 CAN_FilterConfigStructure.FilterBank = 14;
版权声明:本文为CSDN博主「海歌也疯狂」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31094099/article/details/121929435
暂无评论