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!
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