Description

SAMC21_CAN_RECEIVER() – class serves as the base class for user developed classes. The instances of the derived user class will then be ‘registered’ with the SAMC21_CAN global object MCAN0 or MCAN1 by calling regReceiver(). From this moment on, the objects call-back method can_msg_recv_callback will be called whenever a new message (in the defined ID range) is received. A further method can be implemented can_routine_callback which is executed regularly whenever the system is idle (eg. during time when the application calls yield(), delay() and loop()-iterations)

Syntax

class MY_CLASS : public SAMC21_CAN_RECEIVER

{
  public: 
   void can_msg_recv_callback(const CANMessage & inMessage)
   {      }
   void can_routine_callback()
   {     }
};

(code extract from file samc21_can.h)

Example

Define a class that inherits from SAMC21_CAN_RECEIVER():

class MY_ENGINE_CLASS : public SAMC21_CAN_RECEIVER

{
 public:
  uint32_t  u32_RPM;
  uint8_t   s8_Temperature;
  void can_msg_recv_callback(const CANMessage & inMessage)
  {
    if(inMessage.id == 0x123)
      u32_RPM = inMessage.data32[0];
    if(inMessage.id == 0x124)
      s8_Temperature= inMessage.data[0];
  }
  void can_routine_callback()
  {
    // do things regularly
  }
};

Create an instance of the new class and register this object with the SAMC21_CAN class:

MY_ENGINE_CLASS myEngineObj; // create an instance of our class

void setup()
{
  while(!Serial);

  // register obj. with MCAN0 listening for std.IDs 0x123 & 0x124
  MCAN0.regReceiver(&myEngineObj, 0x123, 0x124, 0); 
}
  
void loop()
{
  Serial.println("Engine temperature: "+String(myEngineObj.s8_Temperature));
  Serial.println("Engine RPM: "+String(myEngineObj.u32_RPM));
  delay(1000);
}

An example can be found in the Arduino IDE menu:
File -> Examples -> DICE -> CAN_Bus -> ReceiverClassExample

Notes and Warnings

It is common practise to only do calculations and to set variables in call-back routines.
Do not use any functions like delay(), yields(), println() etc. that would cause the re-entrance of the call-backs.

Be aware that CAN messages that are handled by the SAMC21_CAN_RECEIVER classes will no longer be available to the user application readMsgBuf() calls anymore. So carefully pick the CAN IDs ranges for the SAMC21_CAN_RECEIVER objects that are of interest.

See also

Find more details about the ‘bootloader settings’ and the CAN bus of dice devices
SAMC21_CAN – Library
can_msg_recv_callback()
can_routine_callback()
regReceiver()
deregReceiver()
CAN operation background
users manual
BOOTLOADER SETTINGS – Library