%% 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)

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

%
%% Start the Channel
% Use the start command to set the channel online.

start(rxCh);

%
%% 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.

generateMsgs();

%
%% 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.

rxCh.MessagesAvailable

%
%% Stop the Channel
% Use the stop command to set the channel offline.

stop(rxCh);

%
% Copyright 2008-2021 The MathWorks, Inc.