%% Event-Based CAN Communication in MATLAB
% This example shows you how to configure CAN channels and messages for transmit messages on event. It uses MathWorks virtual CAN channels connected in a loopback configuration.
% As this example is based on sending and receiving CAN messages on a virtual network, running CAN Explorer in conjunction may provide a more complete understanding of what the code is doing. To run CAN Explorer, open and configure it to use the same interface as the receiving channel of the example. Make sure to start CAN Explorer before beginning to run the example in order to see all of the messages as they occur.
% This example describes the workflow for a CAN network, but the concept demonstrated also applies to a CAN FD network.
%
%% Create the CAN Channels
% Create CAN channels for message transmission and reception.

txCh = canChannel("MathWorks", "Virtual 1", 1);
rxCh = canChannel("MathWorks", "Virtual 1", 2);

% Open the DBC-file that contains message and signal definitions, and attach it to both CAN channels.

db = canDatabase("CANDatabaseEvent.dbc");
txCh.Database = db;
rxCh.Database = db;

%
%% Create the CAN Message
% Create CAN message EngineMsg using the database information.

msgEngineMsg = canMessage(db, "EngineMsg")

%
%% Configure the Message for Event-Based Transmission
% To enable a message for event-based transmission, use the transmitEvent command specifying the transmitting channel, the message to register on the channel, and a state value.

transmitEvent(txCh, msgEngineMsg, "On");

%
%% Start the Event-Based Transmission
% Start the receiving and transmitting channels.

start(rxCh);
start(txCh);

% Write new values to the Data property and directly to the VehicleSpeed signal to trigger automatic event-based transmission of the message onto the CAN bus.

msgEngineMsg.Data = [250 100 0 0 20 0 0 0];
pause(1);
msgEngineMsg.Signals.VehicleSpeed = 60;
pause(1);

% Stop the transmitting and receiving channels.

stop(txCh);
stop(rxCh);

%
%% Analyze the Behavior of Event-Based Transmission
% The receiving channel now has two messages available, corresponding to the two updates that resulted in two transmissions.

rxCh.MessagesAvailable

% Receive the available messages. Inspect the messages and note that each has the data values set previously to the Data property.

msgRx = receive(rxCh, Inf, "OutputFormat", "timetable")

% Inspect the signals and note that the second instance of VehicleSpeed has the data value set previously to the VehicleSpeed signal.

signals = canSignalTimetable(msgRx)

%
%% View Messages Configured for Event-Based Transmission
% To see messages configured on the transmitting channel for automatic transmission, use the transmitConfiguration command.

transmitConfiguration(txCh)

%
%% Close the Channels and DBC-File
% Close access to the channels and the DBC-file by clearing their variables from the workspace.

clear rxCh txCh
clear db

%
% Copyright 2010-2021 The MathWorks, Inc.