在使用STM32的CAN控制器进行数据收发,当用到位屏蔽模式的时候,就要设置过滤器了,这个关系到是否能够接收到想要的数据。下面针对几种不同情况对CAN过滤器(Filter)进行设置。
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;//标示符屏蔽模式
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;
1、对扩展数据帧进行过滤:(只接收扩展数据帧)
CAN_FilterInitStructure.CAN_FilterIdHigh=(EXT_ID》》13)&0xFFFF;
CAN_FilterInitStructure.CAN_FilterIdLow=((EXT_ID《《3)|(0x04))&0xFFFF;
//这里设置|0x04(0b0100)就是为了IDE=1,RTR=0,
//这里也可以写为(EXT_ID《《3)|CAN_ID_EXT|CAN_RTR_ROMOTE,效果一样,下同
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0xFFFF;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0xFFFF;
2、对扩展远程帧过滤:(只接收扩展远程帧)
CAN_FilterInitStructure.CAN_FilterIdHigh=(EXT_ID》》13)&0xFFFF;
CAN_FilterInitStructure.CAN_FilterIdLow=((EXT_ID《《3)|(0x06)&0xFFFF;
//这里设置|0x06(0b0110)就是为了IDE=1,RTR=1
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0xFFFF;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0xFFFF;
3、对标准远程帧过滤:(只接收标准远程帧)
CAN_FilterInitStructure.CAN_FilterIdHigh=((STD_ID《《21)&0xFFFF0000)》》16;
CAN_FilterInitStructure.CAN_FilterIdLow=((STD_ID《《21)|(0x0))&0xFFFF;
//这里设置|0x0(0b0000)就是为了IDE=0,RTR=0
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0xFFE0;//0xFFE0表示要关注11位的STD_ID
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0006;//0110,表示要关注IDE和RTR位,只接受标准,不接受扩展
4、对标准数据帧过滤:(只接收标准数据帧)
CAN_FilterInitStructure.CAN_FilterIdHigh=((STD_ID《《21)&0xFFFF0000)》》16;
CAN_FilterInitStructure.CAN_FilterIdLow=((STD_ID_ID《《21)|(0x06))&0xFFFF;
//这里设置|0x02(0b0010)就是为了IDE=0,RTR=1
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0xFFE0;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0006;//只接受标准数据帧,不接受扩展数据帧
相关文章









