| Contents | Index |
| On this page… |
|---|
Examples follow a sequential workflow for configuring CAN communications. Use these examples sequentially MATLAB Command Window.
In the example, create two CAN channels using canChannel, and canHWInfo to obtain information about the devices installed on your system. Edit the properties of the first channel and create a message using canMessage. Transmit the message from the first channel using transmit, and receive it on the other using receive .
Before you follow this example, make sure you:
Complete your toolbox installation before you try out the examples.
Connect the two channels in your CAN device with a loopback connector.
The following examples use the Vector CANcaseXL hardware. You can substitute it with any other supported hardware.
Get information about the CAN hardware devices on your system:
info = canHWInfo
MATLAB displays the following information:
CAN Devices Detected
Vendor | Device | Channel | Serial Number | Constructor
------ | --------------------------- | ------- | ------------- | -------------------------------------
Kvaser | Virtual 1 | 1 | 0 | canChannel('Kvaser', 'Virtual 1', 1)
Kvaser | Virtual 1 | 2 | 0 | canChannel('Kvaser', 'Virtual 1', 2)
NI | Virtual (CAN256) | 1 | 0 | canChannel('NI', 'CAN256')
NI | Virtual (CAN257) | 2 | 0 | canChannel('NI', 'CAN257')
NI | Series 847X Sync USB (CAN0) | 1 | 14E1B6E | canChannel('NI', 'CAN0')
NI | Series 847X Sync USB (CAN1) | 1 | 14E1B68 | canChannel('NI', 'CAN1')
Vector | CANcaseXL 1 | 1 | 24365 | canChannel('Vector', 'CANcaseXL 1', 1)
Vector | CANcaseXL 1 | 2 | 24365 | canChannel('Vector', 'CANcaseXL 1', 2)
Vector | Virtual 1 | 1 | 0 | canChannel('Vector', 'Virtual 1', 1)
Vector | Virtual 1 | 2 | 0 | canChannel('Vector', 'Virtual 1', 2)
Use GET on the output of CANHWINFO for more information.Get details about all available CAN channels by typing:
info.VendorInfo(1).ChannelInfo(1)
Press Enter. MATLAB displays information such as:
can.vector.ChannelInfo handle
Package: can.vector
Properties:
Device: 'CANcaseXL 1'
DeviceChannelIndex: 1
DeviceSerialNumber: 24365
ObjectConstructor: 'canChannel('Vector','CANcaseXL 1',1)'Note This example assumes that you have a loopback connection between the two channels on your CAN device. |
Create the first CAN channel on an installed CAN device:
canch1 = canChannel('Vector','CANcaseXL 1',1)
Press Enter after you create the connection. MATLAB displays a summary of the channel properties:
Summary of CAN Channel using 'Vector' 'CANcaseXL 1' Channel 1.
Channel Parameters: Bus Speed is 500000.
Bus Status is 'N/A'.
Transceiver name is 'CANpiggy 251mag (Highspeed)'.
Serial Number of this device is 24811.
Initialization access is allowed.
No database is attached.
Status: Offline - Waiting for START.
0 messages available to RECEIVE.
0 messages transmitted since last start.
0 messages received since last start.
Filter History: Standard ID Filter: Allow All | Extended ID Filter: Allow All.
Create a second CAN channel object.
canch2 = canChannel('Vector','CANcaseXL 1',2)You used the canChannel function to connect to the CAN device. To identify installed devices, use the canHWInfo function.
You can set the behavior of your CAN channel by configuring its property values. For this exercise, change the bus speed of channel 1 to 250000 using the configBusSpeed function.
Display the properties on canch1:
get(canch1)
MATLAB displays all properties on the configured channel:
General Settings: BusStatus = 'N/A' Database = [] InitializationAccess = 1 MessageReceivedFcn = [] MessageReceivedFcnCount = 1 MessagesAvailable = 0 MessagesReceived = 0 MessagesTransmitted = 0 ReceiveErrorCount = 0 Running = 0 SilentMode = 0 TransmitErrorCount = 0 Device Settings: Device = 'CANcaseXL 1' DeviceChannelIndex = 1 DeviceSerialNumber = 24811 DeviceVendor = 'Vector' Transceiver Settings: TransceiverName = 'CANpiggy 251mag (Highspeed)' TransceiverState = 16 Bit Timing Settings: BusSpeed = 500000 SJW = 1 TSEG1 = 4 TSEG2 = 3 NumOfSamples = 1
Change the BusSpeed property of the channel to 250000:
configBusSpeed(canch1, 250000)
To see the changed property value, type:
get(canch1)
MATLAB displays all properties on the configured channel as before, with the changed BusSpeed property value:
. . . BusSpeed = 250000
Change the bus speed of the second channel (canch2) by repeating steps 2 and 3.
Start your CAN channels after you configure all properties.
Start the first channel:
start(canch1)
Start the second channel:
start(canch2)
To check that the channel is online, type the channel name in the Command Window. The Status section indicates that the channel is now online, as in this example:
>> canch1
.
.
.
Status: Online.
0 messages available to RECEIVE.
0 messages transmitted since last start.
0 messages received since last start.
Filter History: Standard ID Filter: Allow All | Extended ID Filter: Allow All.After you set all the property values as desired and your channels are online, you are ready to transmit and receive messages on the CAN bus. For this exercise, transmit a message using canch and receive it using canch1. To transmit a message, create a message object and pack the message with the required data.
Build a CAN message of ID 500 of standard type and a data length of 8 bytes:
messageout = canMessage(500, false, 8)
The message object is now:
messageout =
can.Message handle
Package: can
Properties:
ID: 500
Extended: 0
Name: ''
Database: []
Error: 0
Remote: 0
Timestamp: 0
Data: [0 0 0 0 0 0 0 0]
Signals: []
Methods, Events, Superclasses
The fields in the message show:
can.Message (Normal Frame) — Specifies that the message is not an error or a remote frame.
ID — The ID you specified and its hexadecimal equivalent.
Extended — A logical 0 (false) because you did not specify an extended ID.
Data — A uint8 array of 0s specified by the data length.
Refer to the canMessage function to understand more about the input arguments.
You can also use a database to create a CAN message. Refer to Using a CAN Database for more information.
After you define the message, pack it with the required data.
Use the pack function to pack your message with these input parameters:
pack(messageout, 25, 0, 16, 'LittleEndian')
Here you are specifying the data value to be 25, the start bit to be 0, the signal size to be 16, and the byte order to be little-endian format.
To see the packed data, type:
messageout
MATLAB displays your message properties with the specified data:
messageout =
can.Message handle
Package: can
Properties:
ID: 500
Extended: 0
Name: ''
Database: []
Error: 0
Remote: 0
Timestamp: 0
Data: [25 0 0 0 0 0 0 0]
Signals: []
Methods, Events, SuperclassesThe only field that changes after you specify the data is Data. Refer to the pack function to understand more about the input arguments.
After you define the message and pack it with the required data, you are ready to transmit the message. For this example, use canch to transmit the message.
Use the transmit function to transmit the message, supplying the channel and the message as input arguments:
transmit(canch1, messageout)
To display the channel status, type:
canch1
MATLAB displays the updated status of the channel:
Summary of CAN Channel using 'Vector' 'CANcaseXL 1' Channel 1.
Channel Parameters: Bus Speed is 250000.
Bus Status is 'ErrorPassive'.
Transceiver name is 'CANpiggy 251mag (Highspeed)'.
Serial Number of this device is 24811.
Initialization access is allowed.
No database is attached.
Status: Online.
1 messages available to RECEIVE.
1 messages transmitted since last start.
0 messages received since last start.
Filter History: Standard ID Filter: Allow All | Extended ID Filter: Allow All.In the Status section, messages transmitted since last start count increments by 1 each time you transmit a message.
Refer to the transmit function to understand more about the input arguments.
After your channel is online, use the receive function to receive available messages. For this example, receive the message on the second configured channel object, canch2.
To see messages available to be received on this channel, type:
canch2
The channel status displays available messages:
.
.
.
Status: Online.
1 messages available to RECEIVE.
0 messages transmitted since last start.
0 messages received since last start.To receive one message from canch1 and store it as messagein, type:
messagein = receive(canch2, 1)
MATLAB returns the received message properties:
messagein =
can.Message handle
Package: can
Properties:
ID: 500
Extended: 0
Name: ''
Database: []
Error: 0
Remote: 0
Timestamp: 709.0403
Data: [25 0 0 0 0 0 0 0]
Signals: []
Methods, Events, SuperclassesTo check if the channel received the message, type:
canch2
MATLAB returns the channel properties, and the status indicates that the channel received one message:
.
.
.
Status: Online.
0 messages available to RECEIVE.
0 messages transmitted since last start.
1 messages received since last start.Refer to the receive function to understand more about its input arguments.
After your channel receives a message, specify how to unpack the message and interpret the data in the message. Use unpack to specify the parameters for unpacking a message:
value = unpack(messagein, 0, 16, 'LittleEndian', 'int16')
The unpacked message returns a value based on your parameters:
value =
25Refer to the unpack function to understand more about its input arguments.
You can save a CAN channel object to a file using the save function anytime during the CAN communication session.
For example, create a channel object canch1. To save it to the MATLAB file mycanch.mat, type:
save mycanch.mat canch1
If you have saved a CAN channel as a MATLAB file, you can load it into a session using the load function. For example, to reload mycanch.mat created above, type:
load mycanch.mat
The loaded CAN channel object reconnects to the specified hardware and reconfigures itself to the specifications when the channel was saved.
You can set up filters on your channel to accept messagees based on the filtering parameters you specify. Set up your filters before putting your channel online. For more information on message filtering, see these functions:
To specify message names you want to filter, create a CAN channel and attach a database to the channel:
canch1=(Vector','CANcaseXL 1',1);
canch1.Database=('demoVNT_CANdbFiles.dbc');
Set a filter for the message EngineMsg and display the channel:
filterAllowOnly(canch1, 'EngineMsg');
canch1
Summary of CAN Channel using 'Vector' 'CANcaseXL 1' Channel 1.
Channel Parameters: Bus Speed is 500000.
Bus Status is 'N/A'.
Transceiver name is ''.
Serial Number of this device is 0.
Initialization access is allowed.
'demoVNT_CANdbFiles.dbc' database is attached.
Status: Offline - Waiting for start.
0 messages available to receive.
0 messages transmitted since last start.
0 messages received since last start.
Filter History: Standard ID Filter: Allow Only | Extended ID Filter: Allow AllIf you start the channel and receive messages, you should now only see the EngineMsg pass through the filter.
Use multiplexing to represent multiple signals in one signal's location in a CAN message's data. A multiplexed message can have three types of signals:
This signal is always active. You can create one or more standard signals.
Also called the mode signal, it is always active and its value determines which multiplexed signal is currently active in the message data. You can create only one multiplexor signal per message.
This signal is active when its multiplex value matches the value of the multiplexor signal. You can create one or more multiplexed signals in a message.
Multiplexing works only with a CAN database with message definitions that already contain multiplex signal information. This example shows you how to access the different multiplex signals using a database constructed specifically for this purpose. This database has one message with these signals:
SigA: A multiplexed signal with a multiplex value of 0.
SigB: Another multiplexed signal with a multiplex value of 1.
MuxSig: A multiplexor signal, whose value determines which of the two multiplexed signals are active in the message.
Create a CAN database:
d = canDatabase('Mux.dbc')Create a CAN message:
m = canMessage(d, 'Msg')
The message displays all its properties:
m =
can.Message handle
Package: can
Properties:
ID: 250
Extended: 0
Name: 'Msg'
Database: [1x1 can.Database]
Error: 0
Remote: 0
Timestamp: 0
Data: [0 0 0 0 0 0 0 0]
Signals: [1x1 struct]
Methods, Events, SuperclassesTo display the signals, type:
m.Signals
ans =
SigB: 0
SigA: 0
MuxSig: 0MuxSig is the multiplexor signal, whose value determines which of the two multiplexed signals are active in the message. SigA and SigB are the multiplexed signals that are active in the message if their multiplex values match MuxSig. In the example shown, SigA is active because its current multiplex value of 0 matches the value of MuxSig (which is 0).
If you want to make SigB active, change the value of the MuxSig to 1:
m.Signals.MuxSig = 1
To display the signals, type:
m.Signals
ans =
SigB: 0
SigA: 0
MuxSig: 1SigB is now active because its multiplex value of 1 matches the current value of MuxSig (which is 1).
Change the value of MuxSig to 2:
m.Signals.MuxSig = 2
Here, neither of the multiplexed signals are active because the current value of MuxSig does not match the multiplex value of either SigA or SigB.
m.Signals
ans =
SigB: 0
SigA: 0
MuxSig: 2Always check the value of the multiplexor signal before using a multiplexed signal value.
if (m.Signals.MuxSig == 0) % Feel free to use the value of SigA however is required. end
This ensures that you are not using an invalid value because the toolbox does not prevent or protect reading or writing inactive multiplexed signals.
Note You can access both active and inactive multiplexed signals regardless of the value of the multiplexor signal. |
Refer to the canMessage function to learn more about creating messages.
The SilentMode property of a CAN channel specifies that the channel can only receive messages and not transmit them. Use this property to observe all message activity on the network and perform analysis without affecting the network state or behavior. See SilentMode for more information.
Create a CAN channel object canch and display its properties:
get(canch1)
MATLAB displays all properties on the configured channel:
General Settings: BusStatus = 'N/A' Database = [] InitializationAccess = 1 MessageReceivedFcn = [] MessageReceivedFcnCount = 1 MessagesAvailable = 0 MessagesReceived = 0 MessagesTransmitted = 0 ReceiveErrorCount = 0 Running = 0 SilentMode = 0 TransmitErrorCount = 0 Device Settings: Device = 'CANcaseXL 1' DeviceChannelIndex = 1 DeviceSerialNumber = 24811 DeviceVendor = 'Vector' Transceiver Settings: TransceiverName = 'CANpiggy 251mag (Highspeed)' TransceiverState = 16 Bit Timing Settings: BusSpeed = 500000 SJW = 1 TSEG1 = 4 TSEG2 = 3 NumOfSamples = 1
Change the SilentMode property of the channel to true:
canch1.SilentMode = true
To see the changed property value, type:
get(canch1)
MATLAB displays all properties on the configured channel as before, with the changed SilentMode property value:
. . . SilentMode = 1 . . .
When you no longer need to communicate with your CAN bus, disconnect the CAN channel that you configured. Use the stop function to disconnect.
Stop the first channel:
stop(canch1)
Check the channel status:
canch1
MATLAB displays the channel status:
.
.
.
Status: Offline - Waiting for START.
1 messages available to RECEIVE.
1 messages transmitted since last start.
0 messages received since last start.Stop the second channel:
stop(canch2)
Check the channel status:
canch2
MATLAB displays the channel status:
Status: Offline - Waiting for START.
0 messages available to RECEIVE.
0 messages transmitted since last start.
1 messages received since last start.When you no longer need the objects you used, remove them from the MATLAB workspace. To remove channel objects and other variables from the MATLAB workspace, use the clear function.
Clear the first channel:
clear canch1
Clear the second channel:
clear canch2
Clear the CAN messages:
clear('messageout', 'messagein')Clear the unpacked value:
clear value
![]() | Vehicle Network Communication in MATLAB | Accessing the Toolbox | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |