STM32的CAN过滤

文章目录

  • 简介
  • 相关寄存器
  • 代码实例
    • 只过滤一个CAN ID
    • 过滤多个CAN ID

简介

  STM32CAN控制器可以对接收到的数据报文进行过滤。

  1. 只接收指定CAN ID的数据。
  2. 对于其他CAN ID发送过来的数据,则不再触发CAN中断。

  根据芯片的不同,可以有不同数量的CAN控制器:

  • 如果STM32只有一个CAN控制器,则可以配置14个过滤器组,对应的编号为0 ~ 13
  • 如果STM32拥有两个CAN控制器,则可以配置28个过滤器组:
  1. 对于CAN 1,对应的过滤器组编号为0 ~ 13
  2. 对于CAN 2,对应的过滤器组编号为14 ~ 27

  CAN过滤有如下模式:

  • 屏蔽位模式
  • 标识符列表模式

相关寄存器

  和CAN过滤相关的寄存器为CAN_FxR1CAN_FxR2

STM32的CAN过滤_第1张图片

  如果只想接收CAN ID0x317的标准帧,则设置方法如下:

在这里插入图片描述

  • 0110 0010 1110x317对应的二进制位。
  • 1111 1111 111:收到的数据帧中相应的ID位必须和设置的ID位一样。
  • 0011:只接收标准帧,不接收扩展帧。

  如果想接收CAN ID0x3100x317的标准帧,则设置方法如下:

在这里插入图片描述

代码实例

只过滤一个CAN ID

  如果需要让CAN 2只接收CAN ID0x713的报文,则代码如下:

CAN_FilterInitTypeDef CAN_FilterInitStructure;

CAN_FilterInitStructure.CAN_FilterNumber = 14;
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;

CAN_FilterInitStructure.CAN_FilterIdHigh     = ( uint16_t ) ( ( 0x713 << 5 ) & 0xFFFF );
CAN_FilterInitStructure.CAN_FilterIdLow      = ( uint16_t ) ( 0x0000 | CAN_ID_STD );
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0xFFF0;
CAN_FilterInitStructure.CAN_FilterMaskIdLow  = 0x0006;

CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit ( &CAN_FilterInitStructure );

过滤多个CAN ID

  如果需要让CAN 2只接收CAN ID0x7130x714的报文,则代码如下:

CAN_FilterInitTypeDef CAN_FilterInitStructure;

CAN_FilterInitStructure.CAN_FilterNumber = 14;
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;

CAN_FilterInitStructure.CAN_FilterIdHigh     = ( uint16_t ) ( ( 0x713 << 5 ) & 0xFFFF );
CAN_FilterInitStructure.CAN_FilterIdLow      = ( uint16_t ) ( 0x0000 | CAN_ID_STD );
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0xFFF0;
CAN_FilterInitStructure.CAN_FilterMaskIdLow  = 0x0006;

CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit ( &CAN_FilterInitStructure );
/*-----------------------------------------------------------------------------------*/
CAN_FilterInitStructure.CAN_FilterNumber = 15;
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;

CAN_FilterInitStructure.CAN_FilterIdHigh     = ( uint16_t ) ( ( 0x714 << 5 ) & 0xFFFF );
CAN_FilterInitStructure.CAN_FilterIdLow      = ( uint16_t ) ( 0x0000 | CAN_ID_STD );
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0xFFF0;
CAN_FilterInitStructure.CAN_FilterMaskIdLow  = 0x0006;

CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit ( &CAN_FilterInitStructure );

你可能感兴趣的:(stm32,单片机,arm)