MATLAB Examples

CAN Message Reception Callback Functions

This example shows you how to configure and use a callback function to receive and process messages received from a CAN channel. It uses MathWorks Virtual CAN channels connected in a loopback configuration.

Contents

Create a Receiving Channel

Create a CAN channel 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 a callback function on the channel to trigger via incoming messages.

rxCh.MessageReceivedFcn = @receivingFcn;

Configure the Message Received Count

Specify an available message threshold to control the quantity of messages required in the channel before the callback function is triggered.

rxCh.MessageReceivedFcnCount = 30;

Implement the Callback Function

The example callback function receives message from the channel on each execution 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])
    xlabel('Timestamp');
    ylabel('CAN Identifier');
    hold all;
end

Start the Channel

Use the start command to set the channel online.

start(rxCh);

Execute the Callback Function

The example function generateMsgs creates CAN messages and transmits them at various periodic rates. It creates traffic on the CAN bus for example purposes and is not part of the Vehicle Network Toolbox™. As the messages are transmitted, the callback function executes each time the message received function count threshold is met.

generateMsgs();

Inspect the Remaining Messages

Note the remaining messages in the channel. Since the available message count is below the threshold specified earlier, more messages are required to trigger the callback another time.

rxCh
rxCh = 

  Channel with properties:

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

   Status Information
                 Running: 1
       MessagesAvailable: 20
        MessagesReceived: 527
     MessagesTransmitted: 0
    InitializationAccess: 1
        InitialTimestamp: 10-Feb-2018 18:43:46
           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: []

Stop the Channel

Use the stop command to set the channel offline.

stop(rxCh);