%% Get Started with CAN FD Communication in MATLAB
% This example shows you how to use CAN FD channels to transmit and receive CAN FD messages. It uses MathWorks virtual CAN FD channels connected in a loopback configuration.
%
%% View Available CAN FD Channels
% Use canFDChannelList to see all available device channels supporting CAN FD.

canFDChannelList

%
%% Create Transmitting and Receiving Channels
% Use canFDChannel with device details specified to create CAN FD channels for transmitting and receiving messages.

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

%
%% Configure Bus Speed
% CAN FD channels require setting of bus speed before going online. Both the arbitration and data phase speeds are configured using configBusSpeed.

configBusSpeed(txCh, 500000, 1000000);
configBusSpeed(rxCh, 500000, 1000000);

%
%% Open the DBC-File
% Use canDatabase to open the database file that contains definitions of CAN FD messages and signals.

db = canDatabase("CANFDExample.dbc")

% Attach the database directly to the receiving channel. Definitions from the DBC-files are applied automatically to decode incoming messages and signals.

rxCh.Database = db;

%
%% Start the Channels
% Use the start command to set the channels online.

start(txCh);
start(rxCh);

%
%% Create CAN FD Messages
% Create CAN FD messages using the canFDMessage function.

msg1 = canFDMessage(500, false, 12)
msg2 = canFDMessage(1000, false, 24);
msg3 = canFDMessage(1500, false, 64);

% To engage the bit rate switch capability of CAN FD, set the BRS property of the messages.

msg1.BRS = true;
msg2.BRS = true;
msg3.BRS = true;

% CAN FD messages can also be created using a database. The database defines if a message is CAN or CAN FD as well as the BRS status.

msg4 = canFDMessage(db, "CANFDMessage")

%
%% Transmit Messages
% Use transmit to send the created messages from the transmitting channel.

transmit(txCh, [msg1 msg2 msg3 msg4])

%
%% Receive Messages
% Receive the messages from the receiving channel using the receive function. The default return type for CAN FD channels is a timetable containing information specific to the received CAN FD messages.

rxMsg = receive(rxCh, Inf)

%
%% Stop the Channels
% Use the stop command to set the channels offline.

stop(txCh);
stop(rxCh);

%
%% Close the DBC-File
% Close access to the DBC-file by clearing its variable from the workspace.

clear db

%
% Copyright 2017-2021 The MathWorks, Inc.