Main Content

Use Message Reception Callback Functions in CAN Communication

This example shows you how to use a callback function to process messages received from a CAN channel. It uses MathWorks virtual CAN channels connected in a loopback configuration. This example describes the workflow for a CAN network, but the concept demonstrated also applies to a CAN FD network.

Create a Receiving Channel

Create a CAN channel using canChannel to receive messages by specifying the vendor name, device name, and device channel index.

rxCh = canChannel("MathWorks", "Virtual 1", 2)
rxCh = 
  Channel with properties:

   Device Information
            DeviceVendor: 'MathWorks'
                  Device: 'Virtual 1'
      DeviceChannelIndex: 2
      DeviceSerialNumber: 0
            ProtocolMode: 'CAN'

   Status Information
                 Running: 0
       MessagesAvailable: 0
        MessagesReceived: 0
     MessagesTransmitted: 0
    InitializationAccess: 1
        InitialTimestamp: [0x0 datetime]
           FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All'

   Channel Information
               BusStatus: 'N/A'
              SilentMode: 0
         TransceiverName: 'N/A'
        TransceiverState: 'N/A'
       ReceiveErrorCount: 0
      TransmitErrorCount: 0
                BusSpeed: 500000
                     SJW: []
                   TSEG1: []
                   TSEG2: []
            NumOfSamples: []

   Other Information
                Database: []
                UserData: []

Configure the Callback Function

Set the callback function to run when a required number of messages are available on the channel.

rxCh.MessageReceivedFcn = @receivingFcn;

Configure the Message Received Count

Specify the number of messages required in the channel before the callback function is triggered.

rxCh.MessageReceivedFcnCount = 30;

Implement the Callback Function

The example callback function receives all available messages from the channel and plots the CAN identifiers against their timestamps on each execution.

type receivingFcn
function receivingFcn(rxCh)
% RECEIVINGFCN A CAN channel message receive callback function.
%   This is a callback function used to receive CAN message. It receives 
%   messages from the channel RXCH and plots the result.

% Copyright 2009-2016 The MathWorks, Inc.

    % Receive all available messages.
    rxMsg = receive(rxCh, Inf, 'OutputFormat', 'timetable');

    % Plot the signal values against their message timestamps.
    plot(rxMsg.Time, rxMsg.ID, 'x');
    ylim([0 2047])
    ylabel('CAN Identifier');
    hold all;

Start the Channel

Use the start command to set the channel online.


Execute the Callback Function

The function generateMsgs creates CAN messages and transmits them at various periodic rates to create traffic on the CAN bus. As the messages are transmitted, the callback function executes each time the threshold specified by property MessageReceivedFcnCount is met.


Figure contains an axes object. The axes object contains 13 objects of type line.

Inspect the Remaining Messages

Display the MessagesAvailable property of the channel to see the number of remaining messages. Since the available message count is below the specified threshold, more messages are required to trigger the callback another time.

ans = 21

Stop the Channel

Use the stop command to set the channel offline.