Search code examples
stm32can-bushal

Set CAN Filter to a specific ID STM32


I need to set a CAN Filter to ID "$7E8". But I need to set a ID High, Low and a Mask.

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

I found this Article: https://schulz-m.github.io/2017/03/23/stm32-can-id-filter/

And tried that code:

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

But it doesn't recognise a message sent with $7E8


Solution

  • The following works for me. id0 and id1 are two message IDs you want to allow (in ID list mode, you always set two per filter bank). If you want to set just one, I assume you can repeat the first one.

    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();
    }