here is a simple example of setting masks and filters to receive a range if IDs and using an if() statement to check if ID is 5
// demo: CAN-BUS Shield, receive data and set mask and filter
#include <SPI.h>
#include "mcp_can.h"
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 10;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
unsigned char flagRecv = 0;
unsigned char len = 0;
unsigned char buf[8];
char str[20];
void setup()
{
Serial.begin(115200);
while (CAN_OK != CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k
{
Serial.println("CAN BUS Shield init fail");
Serial.println(" Init CAN BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
// set mask, set both the mask to 0x3ff
CAN.init_Mask(0, 0, 0x3ff); // there are 2 mask in mcp2515, you need to set both of them
CAN.init_Mask(1, 0, 0x3ff);
// set filter, we can receive id from 0x04 ~ 0x09
CAN.init_Filt(0, 0, 0x04); // there are 6 filter in mcp2515
CAN.init_Filt(1, 0, 0x05); // there are 6 filter in mcp2515
CAN.init_Filt(2, 0, 0x06); // there are 6 filter in mcp2515
CAN.init_Filt(3, 0, 0x07); // there are 6 filter in mcp2515
CAN.init_Filt(4, 0, 0x08); // there are 6 filter in mcp2515
CAN.init_Filt(5, 0, 0x09); // there are 6 filter in mcp2515
}
void loop()
{
if(CAN_MSGAVAIL == CAN.checkReceive()) // check if data coming
{
flagRecv = 0; // clear flag
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
Serial.println("\r\n------------------------------------------------------------------");
long int id;
Serial.print("Get Data From id: ");
Serial.println(id=CAN.getCanId());
for(int i = 0; i<len; i++) // print the data
{
Serial.print("0x");
Serial.print(buf[i], HEX);
Serial.print("\t");
}
if(id == 0x5) Serial.println("\nID 5 received"); // << check ID == 5
Serial.println();
}
}
a run gives
CAN BUS Shield init ok!
------------------------------------------------------------------
Get Data From id: 7
0x55 0x55 0x55 0x55 0x55 0x50 0x0 0x0
------------------------------------------------------------------
Get Data From id: 5
0x55 0x55 0x55 0x55 0x55 0x50 0x0 0x0
ID 5 received
------------------------------------------------------------------
Get Data From id: 8
0x55 0x55 0x55 0x55 0x55 0x50 0x0 0x0