Built-in CAN Library Issues

I am trying to use the new Arduino R4 Wifi to receive CAN data. I have the hardware set up but I'm having issues finding support online on how exactly to set up the code to receive and manipulate the data I receive over CAN. Arduino included this default read example listed below:

/**************************************************************************************
 * INCLUDE
 **************************************************************************************/

#include <Arduino_CAN.h>

/**************************************************************************************
 * SETUP/LOOP
 **************************************************************************************/

void setup()
{
  Serial.begin(115200);
  while (!Serial) { }

  if (!CAN.begin(CanBitRate::BR_500k))
  {
    Serial.println("CAN.begin(...) failed.");
    for (;;) {}
  }
}

void loop()
{
  if (CAN.available())
  {
    CanMsg const msg = CAN.read();
    Serial.println(msg);
  }
}

But I need to access the individual data bytes in each CAN message and also read the ID. I haven't been able to find any examples online using Arduino's CAN library on how I can go about doing this. Any help is greatly appreciated!

I have not done anything with CAN before, but a quick look at the CanMsg class:\

It appears like everything in the class is public: and it has the data members:

  uint32_t id;
  uint8_t  data_length;
  uint8_t  data[MAX_DATA_LENGTH];

So I would think you could do things like:
if (msg.id == MY_ID) ...
And walk the data using the data_length and data members.

Check Arduino UNO R4 Minima CAN Bus
or Arduino UNO R4 WiFi CAN Bus
Use SN65HVD230 breakout module and connect 120ohm resistor across CANH-CANL terminals.

Hi chrisciak, I might be late, but would like to share following code that works for me:

void loop() {
  if (CAN.available())
  {
    CanMsg const msg = CAN.read();
    unsigned char buf[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    idmessaggio= msg.getStandardId();
    Serial.print("IDMessaggio= ");
    Serial.println(idmessaggio);
    for (int i = 0; i < 6; i++) { //6 is number of bytes transmitted that must be received here     
      buf[i]=msg.data[i]; // stores buf[0....5] with received bytes 
    }
    Serial.println("*+*+*+");
    for (int i=0; i<6; i++){
      Serial.print(buf[i]);
      Serial.print("++");
    }
  }

}

The key is the undocumented usage of

buf[i]=msg.data[i];

which I've tried out of desperation and by imitating other libraries. There is no documentation on Earth about msg.data[i] !

Tested with my working canbus with running Arduino Nano Every + MCP2515 and Arduino MKR WIFI1010 + CanBusShield and IT WORKS :slight_smile:

Hope will provide some help to you.
Andrea