A busy CAN bus carries thousands of frames per second, and most of them are not for your node. Reading every frame in software costs CPU time and, if the code is slow, makes the receive buffer overflow. The CAN controller can reject unwanted IDs in hardware before they reach your code. To use that, you need to turn "I want IDs 0x120 and 0x123" into a filter value and a mask.

The rule

Every ID filter works the same way:

Example
frame passes  if  (received ID AND mask) == (filter ID AND mask)
  • A mask bit of 1 means "this bit must match the filter".
  • A mask bit of 0 means "don't care".

With filter 0x100 and mask 0x7F0, the lower four bits are don't-care, so IDs 0x100 to 0x10F pass:

Example
mask     111 1111 0000   (0x7F0)
filter   001 0000 0000   (0x100)
0x10A    001 0000 1010   upper 7 bits match -> passes
0x110    001 0001 0000   bit 4 differs      -> rejected

A mask of 0x7FF passes exactly one ID. A mask of 0x000 passes everything.

Calculate the filter for a set of IDs

Start from the IDs you want. Any bit that differs between them has to be don't-care, and every bit that is the same in all of them can be checked. This function finds that mask and counts what else slips through:

Python
def accepts(can_id, filter_id, mask):
    """A frame passes when its ID matches the filter in every bit the mask marks with 1."""
    return (can_id & mask) == (filter_id & mask)


def filter_for(ids, width=11):
    """Smallest filter/mask pair that passes all the given IDs, and every ID it lets through."""
    all_ones = (1 << width) - 1
    differ = 0
    for can_id in ids:
        differ |= can_id ^ ids[0]  # bits that are not the same in every wanted ID
    mask = all_ones & ~differ
    filter_id = ids[0] & mask
    passed = [i for i in range(all_ones + 1) if accepts(i, filter_id, mask)]
    return filter_id, mask, passed


for wanted in (list(range(0x100, 0x110)), [0x120, 0x123], [0x120, 0x1A0], [0x123, 0x456]):
    filter_id, mask, passed = filter_for(wanted)
    label = f"0x{wanted[0]:03X}-0x{wanted[-1]:03X}" if len(wanted) > 2 else " and ".join(f"0x{i:03X}" for i in wanted)
    print(f"{label:<18} filter 0x{filter_id:03X}  mask 0x{mask:03X}  passes {len(passed):3} IDs, "
          f"{len(passed) - len(wanted)} unwanted")

Output:

Example
0x100-0x10F        filter 0x100  mask 0x7F0  passes  16 IDs, 0 unwanted
0x120 and 0x123    filter 0x120  mask 0x7FC  passes   4 IDs, 2 unwanted
0x120 and 0x1A0    filter 0x120  mask 0x77F  passes   2 IDs, 0 unwanted
0x123 and 0x456    filter 0x002  mask 0x28A  passes 128 IDs, 126 unwanted

The last line is the trap. 0x123 and 0x456 differ in seven bits, so one mask has to ignore all seven and lets 128 IDs through. Give each of them its own filter instead. The rules of thumb:

  • IDs that differ only in their low bits, like a block of messages from one ECU, share one filter well.
  • IDs that differ in their high bits each need their own filter, or an exact-match (list) filter if your controller has one.
  • "Unwanted" frames still reach your software, so the code must check the ID anyway. The filter only reduces the load.

Filters on Linux

SocketCAN uses the same rule with can_id and can_mask. In Python with python-can:

Python
import can

filters = [
    {"can_id": 0x100, "can_mask": 0x7F0, "extended": False},  # 0x100 to 0x10F
    {"can_id": 0x7E8, "can_mask": 0x7F8, "extended": False},  # OBD-II replies 0x7E8 to 0x7EF
]
with can.Bus(interface="socketcan", channel="can0", can_filters=filters) as bus:
    for msg in bus:
        print(msg)

Tested on python-can's virtual bus, frames with IDs 0x0FF, 0x100, 0x10F, 0x110, 0x7E0, 0x7E8, 0x7EF and 0x7DF give only 0x100, 0x10F, 0x7E8 and 0x7EF.

With can-utils, the filter goes after the interface name as id:mask:

Terminal
candump can0,100:7F0,7E8:7F8

A ~ instead of : inverts the filter and shows everything except the matching IDs, for example candump can0,7DF~7FF hides the OBD-II functional requests. On SocketCAN the filtering happens in the kernel, not in the CAN controller, so it saves your program work but not the driver.

Mailboxes and FIFOs

After the filter, received frames go into receive buffers. Controllers organise them in two ways:

DesignHow it worksTypical use
MailboxesEach buffer has its own filter and holds the latest frame for that IDA fixed set of known messages, each read by its own task
FIFOFrames that pass the filters queue up in arrival orderLogging, gateways, protocol stacks that see many IDs

Both lose data the same way: if software does not read a buffer before the next matching frame arrives, the old frame is overwritten or the new one is dropped, and the controller sets an overrun flag. Check that flag. A receive path that loses frames at 80 % bus load but not at 20 % points to an overrun rather than wiring.

On the transmit side, a controller with several transmit mailboxes has to decide which pending frame to send next. Some send the lowest ID first, as arbitration would; others send in the order the frames were queued, and some let you choose. If a low-priority frame sits in the only transmit buffer while it keeps losing arbitration, a high-priority frame queued behind it waits too. Keep a free mailbox for urgent messages, or use ID-ordered transmission.

Checklist for a new node

  1. List every ID the node must receive, from its DBC.
  2. Group IDs that share upper bits; calculate one filter and mask per group with the function above.
  3. Check how many unwanted IDs each mask passes, and split groups that pass too many.
  4. Count the filters your controller has. If you run out, accept a few unwanted IDs rather than dropping wanted ones.
  5. Read receive buffers in an interrupt or a fast task, and monitor the overrun flag.
  6. On 29-bit networks, remember the mask is 29 bits wide and that the IDE bit decides whether a filter applies to 11-bit or 29-bit frames.

Frequently asked questions

How do I calculate a CAN filter mask?

XOR every wanted ID with the first one and OR the results: that gives the bits that differ. Invert it within 11 bits (or 29) to get the mask. The filter is any wanted ID ANDed with the mask.

What does a mask bit of 0 mean in a CAN filter?

Don't care. The ID bit at that position can be 0 or 1 and the frame still passes. A mask of all ones passes exactly one ID; a mask of all zeros passes every ID.

What is the difference between CAN mailboxes and a FIFO?

A mailbox is a buffer reserved for frames matching its own filter, usually one ID. A FIFO is a queue shared by all frames that pass the filters. Mailboxes suit a fixed set of messages, FIFOs suit logging and gateways.

Why am I losing CAN frames at high bus load?

Usually a receive overrun: software does not empty the buffer before the next frame arrives. Use hardware filters to cut unwanted traffic, read the buffers faster, and check the controller's overrun flag.

References