Filtering Specific Messages on K-CAN with MCP2515

Hi everyone,

I’m working with an MCP2515 CAN module on an Arduino to read messages from a Mini R56 K-CAN bus. Everything is working as expected—I can receive messages without issues—but now I want to filter out unnecessary data and receive only the messages I need.

Specifically, I want to receive only CAN IDs 0x2F8 (time/date) and 0x130 (ignition status) while ignoring everything else.

Here’s my current setup:

#include <SPI.h>
#include <mcp2515.h>

MCP2515 mcp2515(10);
struct can_frame canMsg;

void setup() {
  mcp2515.reset();
  mcp2515.setBitrate(CAN_100KBPS, MCP_8MHZ);
  mcp2515.setNormalMode();

  // mcp2515.setFilterMask(MASK0, false, ???);
  // mcp2515.setFilter(RXF0, false, ???);
  // mcp2515.setFilter(RXF1, false, ???);
}

void loop() {
  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
    if (canMsg.can_id == 0x2F8) {
      uint8_t hrs = (canMsg.data[0] & 0xFF);
      uint8_t min = (canMsg.data[1] & 0xFF);
      uint8_t day = (canMsg.data[3] & 0xFF);
      uint8_t month = (canMsg.data[4] & 0xF0) >> 4;

      String time = String(hrs) + ":" + String(min);
      String date = String(day) + " " + String(months[month]);
    }

    if (canMsg.can_id == 0x130) {
      bool keyInserted = (((canMsg.data[2] >> 7) & 0x01) ^ 0x01) != 0;
    }
  }
}

I understand that I need to set masks and filters to accept only the two CAN IDs I need (0x2F8 and 0x130), but I’m unsure how to correctly configure them. How should I set up the masks and filters to ensure I only receive these specific messages? Any help would be greatly appreciated!

I recently had a similar situation. I needed to parse the content of a SMS message to see if a certain word was in the message and only then do something.

I found this example usefull. It explains and uses the "indexOf" command that will look for a specific word (0x2F8 in your case) and return -1 if not found or the position in the string if found.

Yes, but I don't want MCP2515 to read all messages, and then filter them out, I need to filter them out on the MCP2515 module, so the Arduino loop doesn't get overloaded... I'm pretty sure it can be set with setFilterMask, and setFilter, but not sure what to pass there...

I believe those ??? just need to be replaced with the IDs you want to receive 0x2F8 and 0x130

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.