STM32CUBEMX配置图
1.配置CAN引脚。
2.配置MCU时钟
3.配置CAN外设相关的参数、波特率、工作模式等。
CAN波特率的计算
1.因为CAN的时钟是AHB1外设时钟,这里为8MHZ。
2.根据图上的设置,CAN波特率=8M/Prescaler/(Bit Segment 1+Bit Segment 2+Jump Width) Fcan=8/(8+7+1)=500K
3.这里我们用默认的Normal模式。
4.打开CAN中断
5.生成代码之后修改一下代码,代码如下:
CAN_FilterConfTypeDef sFilterConfig;
static CanTxMsgTypeDef TxMassage;
static CanRxMsgTypeDef RxMassage;
main()
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_CAN_Init();
MX_NVIC_Init();
hcan.pTxMsg=&TxMassage;
hcan.pRxMsg=&RxMassage;
Configure_Filter();
HAL_CAN_Receive_IT(&hcan, CAN_FIFO0);
hcan.pTxMsg->StdId=0x123;
hcan.pTxMsg->ExtId=0x123;
hcan.pTxMsg->RTR=CAN_RTR_DATA;
hcan.pTxMsg->IDE=CAN_ID_STD;
hcan.pTxMsg->DLC=8;
hcan.pTxMsg->Data[0] = 1;
hcan.pTxMsg->Data[1] = 2;
hcan.pTxMsg->Data[2] = 3;
hcan.pTxMsg->Data[3] = 4;
hcan.pTxMsg->Data[4] = 5;
hcan.pTxMsg->Data[5] = 6;
hcan.pTxMsg->Data[6] = 7;
hcan.pTxMsg->Data[7] = 8;
if(HAL_CAN_Transmit(&hcan, 10) != HAL_OK)//测试一下是否能正常发送。
{
/* Transmition Error */
//Error_Handler();
}
while (1)
{
if(Flag_CANRxOver==1)
{
Flag_CANRxOver=0;
hcan.pTxMsg->StdId = hcan.pRxMsg->StdId;
hcan.pTxMsg->Data[0] = hcan.pRxMsg->Data[0];
hcan.pTxMsg->Data[1] = hcan.pRxMsg->Data[1];
hcan.pTxMsg->Data[2] = hcan.pRxMsg->Data[2];
hcan.pTxMsg->Data[3] = hcan.pRxMsg->Data[3];
hcan.pTxMsg->Data[4] = hcan.pRxMsg->Data[4];
hcan.pTxMsg->Data[5] = hcan.pRxMsg->Data[5];
hcan.pTxMsg->Data[6] = hcan.pRxMsg->Data[6];
hcan.pTxMsg->Data[7] = hcan.pRxMsg->Data[7];
if(HAL_CAN_Transmit(&hcan, 10) != HAL_OK)//发送刚刚接收到的CAN数据
{
/* Transmition Error */
//Error_Handler();
}
}
}
}
void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan)
{
HAL_CAN_Receive_IT(hcan, CAN_FIFO0);
Flag_CANRxOver=1;
}
void Configure_Filter(void)
{
sFilterConfig.FilterNumber = 0; //过滤器组0
sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK; //标识符屏蔽位模式
sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;//滤波器位宽为单个32位
sFilterConfig.FilterIdHigh =(((unsigned int)0x0000<<3)&0xFFFF0000)>>16; //要过滤的ID高位,因为这个代码设置不是过滤ID的,所以随意填了一个ID
sFilterConfig.FilterIdLow = (((unsigned int)0x0000<<3)|CAN_ID_STD|CAN_RTR_DATA)&0xFFFF;//要过滤的ID低位
//sFilterConfig.FilterMaskIdHigh = 0xffff;
//sFilterConfig.FilterMaskIdLow = 0xffff; //1表示来自发送端的ID与接收端FilterId匹配才接收数据
sFilterConfig.FilterMaskIdHigh = 0; //这里设置接收任意ID的CAN数据
sFilterConfig.FilterMaskIdLow = 0; //0表示接收来自发送端任意ID的数据
sFilterConfig.FilterFIFOAssignment =CAN_FILTER_FIFO0;//过滤器指向FIFO0;
sFilterConfig.FilterActivation = ENABLE;//使能过滤器
//sFilterConfig.BankNumber = 14;
HAL_CAN_ConfigFilter(&hcan, &sFilterConfig);
}