MCP2515 - Setting Mask + Filter

#include <mcp_can.h>
#include <SPI.h>

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];

MCP_CAN CAN0(9);

void setup() {
  Serial.begin(115200);
  if (CAN0.begin(MCP_STDEXT, CAN_250KBPS, MCP_16MHZ) == CAN_OK) Serial.print("MCP2515 Init Okay!!\r\n");
  else Serial.print("MCP2515 Init Failed!!\r\n");
  pinMode(2, INPUT);  // Setting pin 2 for /INT input

  CAN0.init_Mask(0, 1, 0x1FFFFFFF);  // Init first mask...
  CAN0.init_Filt(0, 1, 0x18FF0108);  // Init first filter...
  CAN0.init_Filt(1, 1, 0x18FF0208);  // Init second filter...

  CAN0.init_Mask(1, 1, 0x1FFFFFFF);  // Init second mask...
  CAN0.init_Filt(2, 1, 0x18FF0308);  // Init third filter...
  CAN0.init_Filt(3, 1, 0x00000000);  // Disable fourth filter...
  CAN0.init_Filt(4, 0, 0x00000000);  // Disable fifth filter...
  CAN0.init_Filt(5, 0, 0x00000000);  // Disable sixth filter...

  Serial.println("MCP2515 Library Mask & Filter Example...");
  CAN0.setMode(MCP_NORMAL);  // Change to normal mode to allow messages to be transmitted
}

void loop() {
  if (!digitalRead(2))  // If pin 2 is low, read receive buffer
  {
    CAN0.readMsgBuf(&rxId, &len, rxBuf);  // Read data: len = data length, buf = data byte(s)
    Serial.print("ID: ");
    Serial.print(rxId, HEX);
    Serial.print(" Data: ");
    for (int i = 0; i < len; i++)  // Print each byte of the data
    {
      if (rxBuf[i] < 0x10)  // If data byte is less than 0x10, add a leading zero
      {
        Serial.print("0");
      }
      Serial.print(rxBuf[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
  }
}

Issue with above code : I expect to read values for 0x18FF0108 , 0x18FF0208, 0x18FF0308. I am effectively filtering the IDs but the Serial monitor prints the IDs as 0x98FF0108 , 0x98FF0208, 0x98FF0308.

What mistake am i doing in setting the Mask ?

all the filters need to be 'set'

since you have only 3 CAN IDs you with to receive, repeat one of those for banks 3, 4 and 5

ie for example:

CAN0.init_Filt(3, 1, 0x18FF0308); 
CAN0.init_Filt(4, 1, 0x18FF0308); 
CAN0.init_Filt(5, 1, 0x18FF0308); 

hope that helps....

I don't think that was the issue ... disabling unused Filters . In fact since I had the system powered up , I did try to change as you suggested and yet the Seril print was this ... 9 in place of 1

indeed...

have a look at the CAN receive example that comes with the library and compare with your code.

notice the how the CAN ID is printed out for extended CAN IDs...

1 Like

OK got it ... Thanks for the pointer !!