目录
- 1. 引脚配置
- 2. 时钟配置
- 3. 代码添加
1. 引脚配置
2. 时钟配置
- CAN配置
波特率计算:500K = 48 / (4+3+1)*12 = 48 / 96
使能中断,很关键,否则CAN无法发送。
3. 代码添加
添加滤波器使能、接收中断使能、CAN使能:
/* Initialize all configured peripherals */MX_GPIO_Init();MX_ADC_Init();MX_CAN_Init();MX_TIM3_Init();/* USER CODE BEGIN 2 *///CAN_Filter_Init(&hcan);CAN1_Filter_Config();HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);HAL_CAN_Start(&hcan);/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */
滤波器使能代码:
void CAN1_Filter_Config()
{
CAN_FilterTypeDef sFilterConfig;sFilterConfig.FilterBank = 0; //
sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;
sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; //
sFilterConfig.FilterIdHigh = 0X0000; //
sFilterConfig.FilterIdLow = 0X0000; //
sFilterConfig.FilterMaskIdHigh = 0X0000; //
sFilterConfig.FilterMaskIdLow = 0X0000; //
sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0; //
sFilterConfig.FilterActivation = ENABLE; //
sFilterConfig.SlaveStartFilterBank = 14; //if(HAL_CAN_ConfigFilter(&hcan, &sFilterConfig) != HAL_OK)
{Error_Handler();
}
}
CAN发送函数:
HAL_CAN_AddTxMessage(&hcan, &CAN_TX_T, tx_data, &tx_mailBox);
CAN接收回调函数:
CAN_RxHeaderTypeDef rxHeader;
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{uint8_t data_ss[8];//HAL_UART_Transmit(&huart1, data_s2, 10, 1000);if(hcan->Instance == CAN){HAL_UART_Transmit(&huart1, data_s1, 10, 1000);HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &rxHeader, data_ss);}}