In a normal CAN BUS is possible to have thousand of message with different IDs, but maybe only a small number of these IDs are useful for your application or test. In order to reduce the number of interrupt for received messages on our device, it is possible to use masks and filters into hardware CAN BUS peripheral.
How do masks and filters work?
On MCP2515 there are 2 masks and 6 filters, MASK 0 is for FILTER 0 and FILTER 1, instead MASK 1 is for FILTER 2, 3, 4, 5.
The MASK is used to select the bits for comparison with FILTER value, for our example we select MASK 0 and its two filters with standard IDs. The same logic is applicable for extended IDs.
- Case 1, mask 0 set with 0x7F0, the 4 last bits of received ID, are not passed to filter 0. The comparison between the first 7 bits of received ID and filter 1 is true. The message goes to RX buffer. With mask 0x7F0 all the IDs from 0x540 to 0x54F pass to RX buffer.
- Case 2, mask 0 set with 0x7F0, the 4 last bits of received ID, are not passed to filter 1. The comparison between the first 7 bits of received ID and filter 1 is false. The message is discarded.
The different masks and filters values must be programmed into the MCP2515.
How to use filters and masks on Raspberry?
On Linux OS is possible to use Socket CAN, a collection of open source can bus tools. If not present install the tools.
sudo apt-get install can-utils
After that there are 4 main functionalities:
- candump, displays messages on the bus in realtime.
- cangen, sends a single CAN frame onto the bus.
- cansend, can generate random CAN data .
- cansniffer, displays frames that are currently on the bus, but filters. out frames with data that is not changing.
The filter is applied at candump tool, if we run the command
we can see all the messages on interface can0, but if we run
candump can0, 0x546:0x7FF
we can see only the ID 0x546. It is possible to add more filters at the same time, for example if we want to see only IDs 0x546 and 0x291 the command is the follow
candump can0, 0x546:0x7FF, 0x291:0x7FF
It is possible to exclude a single ID with the following command
candump can0, 0x546~0x7FF