Longan-Labs / Arduino_CAN_BUS_MCP2515

Arduino CAN Bus library, MCP2515/MCP2551
https://www.longan-labs.cc/
MIT License
128 stars 372 forks source link

Filtering one discret ID #6

Open if2s opened 10 years ago

if2s commented 10 years ago

Hello, I do not know how to recieve only messages with the ID 522 (dec). Can you help me, how to set filter and mask?

255 = 0xFF = 11111111 is it the mask? I do not know..... 522 = 1000001010 (maybe it is the filter? but which filter?)???

I know that I have to use init_Mask(INT8U num, INT8U ext, INT32U ulData); init_Filt(INT8U num, INT8U ext, INT32U ulData);

But what I have to set to num, ext and uIData??????

coryjfowler commented 10 years ago

Set both masks to 0x7FF and all the filters to 0x20A (522 in hex). That should guarantee only 522 is the only ID received.

num is the filter (0 to 5) or mask (0 to 1) to set. ext tells the library if we are using extended (1) or standard (0) IDs. ulData is the number to set.

if2s commented 10 years ago

Thank you. It is working this way but there are some problems with error checking and filtering messages after reset.

I use CAN.checkError() before every reading so that I know if there are some lost frames. The result after an error is permanently CAN_CTRLERROR (5) because datasheet says, eflg has to be reset manually. Maybe it will be a good idea to implement this in library (something like reset_error(void)).

The other problem: My Shield is using in industrial application and I do not have influence if other nodes are sending and with which frequency. So when there is a node sending messages (with IDs which should be blocked) when MCP is initializing, filtering does not work because I only can call init_Mask and init_Filt after CAN.begin is called. Maybe it is better if there is a possibility to set filters and masks before CAN.begin. Example: A node is sending on ID 5 very, very fast all time. When starting sketch I call CAN.begin and init_Mask and init_Filt to receive ID 522 only.

    if(CAN_OK == CAN.begin(CAN_500KBPS))                   // init can bus : baudrate = 500k
    {
        Serial.println("CAN BUS Shield init ok!");
        CAN.init_Mask(0, 0, 0x3FF);
        CAN.init_Mask(1, 0, 0x3FF);
        CAN.init_Filt(0, 0, 0x20A);
        CAN.init_Filt(1, 0, 0x20A);
        CAN.init_Filt(2, 0, 0x20A);
        CAN.init_Filt(3, 0, 0x20A);
        CAN.init_Filt(4, 0, 0x20A);
        CAN.init_Filt(5, 0, 0x20A);
        delay(100);
        Serial.println("masks and filters set!");
    }

The result: No message is filtered. All messages from all IDs arrive the buffer.

If there is no other Node sending data when resetting MCP, the filtering is working find and only ID 522 comes into buffer.