将 CAN Filter 设置为特定 ID STM32

Set CAN Filter to a specific ID STM32

我需要将 CAN 过滤器设置为 ID“$7E8”。但是我需要设置ID High、Low和Mask。

    FilterConfig.FilterIdHigh = 0x0000;
    FilterConfig.FilterIdLow = 0x0000;
    FilterConfig.FilterMaskIdHigh = 0x0000;
    FilterConfig.FilterMaskIdLow = 0x0000;

我找到这篇文章:https://schulz-m.github.io/2017/03/23/stm32-can-id-filter/

并尝试了该代码:

    FilterConfig.FilterIdHigh = 0x00000008;
    FilterConfig.FilterIdLow = 0x00000008;
    FilterConfig.FilterMaskIdHigh = 0x1FFFFFFF;
    FilterConfig.FilterMaskIdLow = 0x1FFFFFFF;

但它无法识别使用 $7E8

发送的消息

以下适合我。 id0id1 是您要允许的两个消息 ID(在 ID 列表模式下,您始终为每个过滤器组设置两个)。如果你只想设置一个,我想你可以重复第一个。

CAN_FilterTypeDef filter;
filter.FilterActivation = ENABLE;
filter.FilterFIFOAssignment = CAN_FILTER_FIFO0;

// Allow two IDs per entry
filter.FilterScale = CAN_FILTERSCALE_16BIT;
filter.FilterMode = CAN_FILTERMODE_IDLIST;

// Mask seems to have no effect when using CAN_FILTERMODE_IDLIST
filter.FilterMaskIdHigh = 0x0000;
filter.FilterMaskIdLow  = 0x0000;

filter.FilterIdLow  = id0;
filter.FilterIdHigh = id1;

filter.FilterBank = 0;

if (HAL_CAN_ConfigFilter(hcan, &filter)) {
    Error_Handler();
}

2 次更正:

  1. 当结合使用 CAN_FILTERSCALE_16BIT 和 CAN_FILTERMODE_IDLIST 时,mask high 和 mask low 变量也包含 11-bit-IDs。您可以通过这种方式为 4 11-bit-IDs 和 ID 列表模式设置滤波器组。
  2. 需要将ID移到相应寄存器中的正确位置。这对于 16 位和 32 位比例是不同的。对于 32 位标度,请参阅微控制器参考手册。对于 16 位比例,这里是一个示例:
  CAN_FilterTypeDef tsCanFilter = { 0 };

  tsCanFilter.FilterActivation     = ENABLE;
  tsCanFilter.FilterFIFOAssignment = CAN_FILTER_FIFO0;
  tsCanFilter.FilterScale          = CAN_FILTERSCALE_16BIT;
  tsCanFilter.FilterMode           = CAN_FILTERMODE_IDLIST;
  
  tsCanFilter.FilterIdLow          = u32Id1 << 5u;
  tsCanFilter.FilterMaskIdLow      = u32Id2 << 5u;
  tsCanFilter.FilterIdHigh         = u32Id3 << 5u;
  tsCanFilter.FilterMaskIdHigh     = u32Id4 << 5u;

  tsCanFilter.FilterBank           = 0u;
  
  if ( HAL_CAN_ConfigFilter ( &tsCanHandle, &tsCanFilter ) != HAL_OK )
  {
    // error handling
  }