%% Get Started with CAN Communication in MATLAB
% This example shows you how to use CAN channels to transmit and receive CAN messages. It uses MathWorks virtual CAN channels connected in a loopback configuration.
%
%% 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);

%
%% Inspect the Channel
% Use the get command to obtain more detailed information on all channel properties and their current values.

get(rxCh)

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

start(rxCh);

%
%% Transmit Messages
% The example function generateMsgs creates CAN messages using canMessage and transmits them using transmit at various periodic rates. It generates traffic on the CAN bus for demonstration purposes.

type generateMsgs

% Run the generateMsgs function to transmit messages for the example.

generateMsgs();

%
%% Receive Messages
% Once generateMsgs completes, receive all available messages from the channel using the receive function.

rxMsg = receive(rxCh, Inf, "OutputFormat", "timetable");

% Use head to extract the first few rows of received messages for preview.

head(rxMsg)

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

stop(rxCh);

%
%% Analyze Received Messages
% MATLAB provides a powerful environment for performing analysis on CAN messages. The plot command can create a scatter plot with message timestamps and identifiers to provide an overview of when certain messages occurred on the network.

plot(rxMsg.Time, rxMsg.ID, "x")
ylim([0 2047])
xlabel("Timestamp")
ylabel("CAN Identifier")

%
% Copyright 2008-2021 The MathWorks, Inc.