关于STM32 CAN的过滤器/滤波器

1.在设置CanTxMsg.StdId时注意需要将其右移一位,比如如下滤波器配置:

CAN_FilterInitStructure.CAN_FilterNumber=0;
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh=0x7f20;
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0xf0f0;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);

使用的是标识符掩码模式,接收到的消息想要通过滤波器则STDID必须是0x7x2,这时我们可以设置 TxMessage.StdId=0x7a2>>1,注意这里必须要右移一位,因为标准标识符的长度是11位,它占用的是CAN_TIxR的高11位,所以在最后组合到CAN_TIxR中时是会被左移21位的,如下:

if (TxMessage->IDE == CAN_Id_Standard)
    {
      assert_param(IS_CAN_STDID(TxMessage->StdId));  
      CANx->sTxMailBox[transmit_mailbox].TIR |= ((TxMessage->StdId << 21) | \
                                                  TxMessage->RTR);
    }

一个数如果被左移4的整数倍那么其还可以保持数字不变,只是值扩大了,如0x7f在左移4位之后是0x7f0,7和f都不变只是最后增加了一个0,左移8位则增加两个0,但是如果是左移3位则变成0x3f8了,数字全变;因此我们这边被左移 21位是会导致数字全变的,所以我们采取的措施就是在赋值的时候主动右移一位,这样它左移21位就相当于原来是只左移20位了。

2.标识符列表模式允许匹配多个ID,你配置了几个滤波器组就可以匹配几个ID,如下:

CAN_FilterInitStructure.CAN_FilterNumber=0;
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdList; 
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh=0x7f20;
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x7f20;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
	
CAN_FilterInitStructure.CAN_FilterNumber=1;
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdList; 
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh=0x7c20;
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x7c20;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);

表示ID为7f20和7c20的都可以通过。

3.在配置为标识符列表模式时 CAN_FilterId 和 CAN_FilterMaskId 必须一样才起效。

 

展开阅读全文

没有更多推荐了,返回首页