一、CAN2通信要注意的问题
从这张图片不难看出can1为主机,can2为从机。因此can2的启动前提是已经启动了can1.
can通讯can2是基于can1的
使用can2之前必须初始化can1
单独使用CAN2时一定要同时打开CAN1和CAN2的时钟,否则CAN2无法正常工作,因为CAN2是从CAN,CAN1是主CAN
因此举例如果使用FIFO0的话,将筛选器分配:
can1的筛选器组就从0开始 范围为0-14
CAN_FilterInitStructure.CAN_FilterNumber=0;
can2的筛选器组就从14开始 范围为14-27
CAN_FilterInitStructure.CAN_FilterNumber=14;
注意:can过滤器配置必须用16进制
如果还是不能用,就要检查CAN芯片的STB引脚是否使能了!!!,这个很重要!
当can正常工作时,STB引脚为低电平,当STB引脚为高电平的时候,CAN总线闲置
void can_filter(CAN_HandleTypeDef* hcan)
{
CAN_FilterTypeDef CAN_FilterConfigStructure;
if (hcan == &hcan2)
{
CAN_FilterConfigStructure.FilterBank = 14;//***********************!!
}
if (hcan == &hcan1)
{
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(hcan, &CAN_FilterConfigStructure);
}
MX_CAN1_Init();//先初始化can1!!!!!
MX_CAN2_Init();
can_filter(hcan1);
can_filter(hcan2);
二、CAN中断无法进入的问题
当邮箱一直被占用后,导致CAN通讯有问题,作为一种保护机制,应该重新进行初始化CAN
问题由来-最近一直在做16s智能电池的通信,可是无人机突然显示hub电压24v(此hub只支持2s-12s电池,无法显示16s电池电压),容易造成低电压返航,实际电压却依旧是64v
一直怀疑是crc校验的问题,最后用fdr进行数据记录,发现是不进电池中断,再往上查发现是整个CAN2中断都不进
所以查问题不要局限于自己的一面,有可能不是自己的问题,逐步扩大排查
transmit_timeout = 0;
while(!(((CANx->TSR)&CAN_TSR_TME0)&&((CANx->TSR)&CAN_TSR_TME1) &&((CANx->TSR)&CAN_TSR_TME2)))
{
transmit_timeout++;
if(transmit_timeout == 65535)
{
if(CANx == CAN1)
{
CAN_DeInit(CAN1);
CAN_DeInit(CAN2);
CAN1_Mode_Init(CAN_SJW_1tq,CAN_BS2_6tq,CAN_BS1_7tq,6,CAN_Mode_Normal);
}
else
{
CAN_DeInit(CAN2);
CAN2_Mode_Init(CAN_SJW_1tq,CAN_BS2_6tq,CAN_BS1_7tq,6,CAN_Mode_Normal);
}
}
}
}