Mathworks VEHICLE NETWORK TOOLBOX 1 user guide

Vehicle Network To
User’s Guide
olbox™ 1
How to Contact The MathWorks
www.mathworks. comp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html T echnical Support
suggest@mathworks.com Product enhancement suggestions
bugs@mathwo doc@mathworks.com Documentation error reports service@mathworks.com Order status, license renewals, passcodes
info@mathwo
com
rks.com
rks.com
Web
Bug reports
Sales, prici
ng, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Vehicle Network Toolbox™ User’s Guide
© COPYR IG HT 2010 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documen tation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Docu mentation, unused, to The Mat hWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
March 2009 Online only New for Version 1.0 (Release 2009a) September 2009 Online only Revised for Version 1.1 (Release 2009b) March 2010 Online only Revised for Version 1.2 (Release 2010a)
Getting Started
1
Product Overview ................................. 1-2
Getting to Know the Vehicle Network Toolbox Main Features Interaction Between the Toolbox and Its Components Expected Background Related P roducts Installation Requirements Supported Hardware
.................................... 1-2
............................. 1-5
.................................. 1-5
.......................... 1-6
............................... 1-7
.......... 1-2
Contents
.... 1-4
CAN Comm unication Session
Workflow O v erview Configuring CAN Communications Saving and Loading a C AN Channel Performing Advanced Configurations Disconnecting Channels and Cleaning Up
Accessing the Toolbox
Exploring the Toolbox Getting Help Viewing Examples
................................ 1-9
.............................. 1-30
.............................. 1-30
..................................... 1-30
................................. 1-30
....................... 1-9
................... 1-11
.................. 1-21
................. 1-22
............. 1-27
Using a CAN Database
2
Vector CA Nd b Support ............................. 2-2
Loading and Creating Messages Using the .dbc File
Loading the CAN Database Creating a CAN Message Accessing Signals in the Constructed CAN Message Adding a Database to a CAN Channel
......................... 2-3
........................... 2-3
................. 2-4
... 2-3
..... 2-4
iii
Updating Database Information ..................... 2-5
Other Uses of the CAN Database
Viewing Message Information in the CAN Database Viewing Signal Information in a CAN Message Attaching a CAN Database to Existing Messages
.................... 2-6
......... 2-7
....... 2-7
Monitoring CAN Message Traffic
3
CAN Tool ......................................... 3-2
Opening the CAN Tool CAN Tool Fields
Using the CAN Tool
Viewing Messages on a Channel Configuring the Channel Bus Speed Saving the Message Log File Viewing Unique Messages
............................. 3-2
.................................. 3-2
................................ 3-6
..................... 3-6
.................. 3-6
........................ 3-7
.......................... 3-7
..... 2-6
iv Contents
Using the Vehicle Network Toolbox Block
4
Overview ......................................... 4-2
Opening the Vehicle Network Toolbox Block
Library
Using the MATLAB Command Window Using the Simulink Library Browser
Building Simulink Models to Transmit and Receive
Messages
Build a Message Transmit Model Build a Message R eceive Model
......................................... 4-3
............... 4-3
.................. 4-4
....................................... 4-5
..................... 4-5
...................... 4-10
Library
Save and Run the Model ............................ 4-17
Function Reference
5
CAN Channel Construction ......................... 5-2
CAN Channel Configuration
CAN Channel Execution
CAN Channel Status
CAN Database
CAN M essage Handling
CAN Message Filtering
Information and Help
Graphical Tools
Vector Informatik
..................................... 5-6
................................... 5-10
............................ 5-4
............................... 5-5
............................ 5-7
............................. 5-8
.............................. 5-9
................................. 5-11
........................ 5-3
v
Functions — Alphabetical List
6
Property Reference
7
CAN Channel Base Properties ...................... 7-2
Channel Status Properties CAN Message Properties CAN Database Properties Receiving Messages Error Logging
................................ 7-3
.................................... 7-4
.......................... 7-2
........................... 7-2
........................... 7-3
Device-Specific Properties
Device Settings Transceiver Settings Bit Timing Settings
8
9
......................... 7-5
................................... 7-5
............................... 7-5
................................ 7-5
Properties — Alphabetical List
Block Reference
Index
vi Contents
Getting Started
“Product Overview” on page 1-2
“CAN Communication Session” on page 1-9
“Accessing the Toolbox” on page 1-30
1
1 Getting Started
Product Overview
Getting to Know the Vehicle Network Toolbox
The Vehicle N etwork Toolbox™ provides the ability to comm unicate with in-vehicle networks using Controller Area Network (CAN) protocol. It is a comprehensive toolbox with a MATLAB support and a sim ple utility that allows you to monitor CAN traffic.
In this section...
“Getting to Know the Vehicle Network Toolbox” on page 1-2
“Main Features” on page 1-2
“Interaction Between the Toolbox and Its Components” on page 1-4
“Expected Background ” on page 1-5
“Related Products” on page 1-5
“Installation Requirements” on page 1-6
“Supported Hardware” on page 1-7
®
interface, Simulink®modeling
1-2
You can learn more about the Vehicle Network Toolbox by following a simple workflow and some easy examples. This chapter introduces the toolbox and provides some guidelines and examples to use the Vehicle Network Toolbox to interface with the CAN bus.
Main Features
The Vehicle Network Toolbox product is a collection of functions built on the MATLAB technical computing environment.
The toolbox provides you with these main features:
“CAN Connectivity” on page 1-3
“Vector Device and Driver Support” on page 1-3
“Vehicle Network Toolbox Functions” on page 1-3
“Simulink Library Support” on page 1-3
Product Overview
“CAN Tool Interface” on page 1-3
CAN Connectivity
The Vehicle Network Toolbox pr ov id es host-side CAN connectivity using defined CAN devices. CAN is the predominant protocol in automotive electronics by which many distributed control systems in a vehicle function.
For example, in a common design when you press a button to lock the doors in your car, a control unit in the door reads that input and transmits lock commands to control units in the other doors. These commands exist as data in CAN messages, which the control units in the other doors receive and act on by triggering their individual locks in response.
Vector Device and Driver Support
You can use the Vehicle Network Toolbox with devices supported by Vector. These devices and drivers provide a link to the CAN bus on which you can send and receive messages.
See “Supported Hardware” on page 1-7 for more information.
Vehicle Network Toolbox Functions
Using a set of well-defined functions, you can transfer messages between the MATLAB workspace and a CAN bus using a CAN device. You can run test applications that can log and record CAN messages for you to process and analyze. You can also replay recorded sequences of messages.
Simulink Library Support
With the Vehicle Network Toolbox block library and other blocks from the Simulink library, you can create sophisticated models to connect to a live network and to simulate message traffic on a CAN bus.
CAN Tool Interface
Using this simple graphical user interface, you can monitor message traffic on a selected device and channel. You can then analyze these messages.
1-3
1 Getting Started
Interaction Bet
The Vehicle Netw bus.
ork Toolbox is a conduit between MATLAB and the CAN
ween the Toolbox and Its Components
1-4
In this illustration:
Six CAN modules are attached to a CAN bus.
One module, which is a CAN device, is attached to the Vehicle Network
Toolbox, built on the MATLAB technical computing environment.
Product Overview
Using the Vehicle Network Toolbox from MATLAB, you can configure a channel on the CAN device to:
Transmit messages to the CAN bus.
Receive messages from the CAN bus.
Trigger a callback function to run when the channel receives a message.
Attach the database to the configured CAN channel to interpret received
CAN messages.
UsetheCANdatabasetoconstructmessagestotransmit.
Log and record messages and analyze them in MATLAB.
Replay live recorded sequence of messages in MATLAB.
Build Simulink models to connect to a CAN bus and to simulate message
traffic.
Monitor message traffic with the CAN Tool.
The Vehicle Network Toolbox is a comprehe ns ive so lutio n for CAN connectivity in MATLAB and Simulink. Refer to the function and block chapters for more information.
Expected Background
This document assumes that you are familiar with these products:
MATLAB — To write scripts and functions, and to use functions with the
command-line interface.
Simulink—TocreatesimplemodelstoconnecttoaCANbusortosimulate
those models.
Vector CANdb — To understand CAN databases and message and signal
definitions.
Related Products
The MathWorks™ provides several products that are relevant to the kinds of tasks you can perform with the Vehicle Network Toolbox software and
1-5
1 Getting Started
that extend the capabilities of MA TLAB . For information about these related products, see the toolbo x product p age on the MathWorks Web site.
Installation Requirements
“Installing Components” on page 1-6
“Installing Vector Hardware Devices and Drivers” on page 1-6
“Installing Kvaser Hardware Devices and Drivers” on page 1-7
“Installing the Toolbox” on page 1-7
Installing Components
To communicate on CAN networks from the MATLAB workspace, install these components:
Current MATLAB version
Vehicle Network Toolbox software
1-6
Hardware, drivers, and driver libraries for your Vector or Kvaser devices
Installing Vector Hardware Devices and Drivers
You need the latest version of the XL Plug & Play drivers for your device to use with Windows
The documentation from Vector provides installation instructions for hardware devices such as CANcaseXL, CANboardXL, and CANcardXL, drivers, and support libraries.
These drivers are available for download from the Vector Web site at:
https://www.vector-worldwide.com/va_downloadcenter_us.html
Installing the XL Driver Library. Download and install the latest version of the XL Driver Library from the Vector Web site. After you install, copy the file
vxlapi.dll from the installation folder to the windows root\system32
directory.
®
XP or Windows Vista™.
Product Overview
Installing Kvaser Hardware Devices and Drivers
You n ee d the latest version of the driver for your device to use with Windows XP or Windows Vista. Refer to your Kvaser device documentation for hardware installation instructions.
Drivers for your Kvaser devices are available on the Kvaser Web site at:
http://www.kvaser.com/download/main.php
Installing the Driver Library. Download and install the latest version of the SDK Driver Library from the Kvaser Web site.
Installing the Toolbox
Determine if Vehicle Network Toolbox software is installed on your system by typing the following in the MATLAB Command Window:
ver
The Command Window displays information about the MATLAB v ersion you are running, including a list of installed add-on products and their version numbers. Check the list to see if the Vehicle Network Toolbox name appears.
For information about installing the toolbox, refer to the installation documentation for your platform. If you experience installation difficulties, look for the installation and license information at the MathWorks Web site:
http://www.mathworks.com/support
Supported Hardware
The Vehicle Network Toolbox supports Vector and Kvaser devices.
Supported Vector Devices
CANcaseXL
CANcaseXLe
CANboardXL
1-7
1 Getting Started
CANboardXL pxi
CANboardXL PCIe
CANcardXL
CANcardX
You can also use the toolbox with virtual CAN channels available with Vector hardware drivers.
Supported Kvaser Devices
Support for Kvaser CAN devices, including these product families:
WLAN
PCMCIA
Leaf
Memorator
1-8
PCI
USB
You can also use the toolbox with virtual CAN channels available with Kvaser hardware drivers.
For a full list of devices, see the Supported Hardware page.
CAN Communication Session
In this section...
“Workflow Overview” on page 1-9
“Configuring CAN Communications” on page 1-11
“Saving and Load ing a CAN Channel” on page 1-21
“Performing Advanced Configurations” on page 1-22
“Disconnecting Channels and Cleaning Up” on page 1-27
Workflow Overview
This section takes you through the workflow for connecting to a CAN device and then communicating with the CAN bus.
The subsequent sections map to the following CAN workflow chart.
CAN Communication Session
Subsequent sections also provide interconnected code examples. You can use these examples and try them sequentially to understand how the communication works.
1-9
1 Getting Started
Typical CAN Workflow
1-10
CAN Communication Session
Configuring CAN Communications
The following sections provide a sequen tial workflow for configuring CAN communications. You can use the provided examples and try them in a MATLAB Command Window to follow along.
This example creates two CAN channel objects using the to obtain information about the devices installedonyoursystem. Youeditthe properties of the first channel and create a message using the function. You transmit the message from the first channel using the transmit function, and receive it on the other using the receive function.
“Prerequisites” on page 1-11
“Checking for the Installed CAN Hardware” on page 1-12
“Creating a CAN Channel Object” on page 1-13
“Configuring Properties” on page 1-14
“Starting the Configured Channel” on page 1-15
“Creating a Message Object” on page 1-16
“Packing a Message” on page 1-17
“Transmitting a Message” on page 1-18
“Receiving a Message” on page 1-19
“Unpacking a Message” on page 1-21
canHWInfo function
canMessage
Prerequisites
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.
1-11
1 Getting Started
Checking for the Installed CAN Hardware
1 Get information about the CAN hardware devices on your system:
info = canHWInfo
MATLAB displays the following information:
CAN Devices Detected:
Vector Devices:
CANcaseXL 1 Channel 1 (SN: 24365)
To connect, use - canChannel('Vector', 'CANcaseXL 1', 1)
CANcaseXL 1 Channel 2 (SN: 24365)
To connect, use - canChannel('Vector', 'CANcaseXL 1', 2)
Virtual 1 Channel 1
To connect, use - canChannel('Vector', 'Virtual 1', 1)
1-12
Virtual 1 Channel 2
To connect, use - canChannel('Vector', 'Virtual 1', 2)
Kvaser Devices:
Virtual 1 Channel 1
To connect, use - canChannel('Kvaser', 'Virtual 1', 1)
Virtual 1 Channel 2
To connect, use - canChannel('Kvaser', 'Virtual 1', 2)
Use GET on the output of CANHWINFO for more information.
2 Get details about all available CAN channels by typing:
info.VendorInfo(1).ChannelInfo(1)
3 Press Enter. M ATLAB displays information such as:
can.vector.ChannelInfo handle
CAN Communication Session
Package: can.vector
Properties:
Device: 'CANcaseXL 1' DeviceChannelIndex: 1 DeviceSerialNumber: 24365
ObjectConstructor: 'canChannel('Vector','CANcaseXL 1',1)'
Creating a CAN Channel Object
Note This example assumes that you have a loopback connection between
the two channels on your CAN device.
1 Create the first CAN channel on an installed CAN device:
canch1 = canChannel('Vector','CANcaseXL 1',1)
Notes You cannot use the same variable to create multiple channels sequentially. Clear any channel in use before using the same variable to construct a new CAN Channel.
You cannot create arrays of CAN channel objects. Each object you create must exist as its own individual variable.
2 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.
1-13
1 Getting Started
Status: Offline - Waiting for START.
0 messages available to RECEIVE.
0 messages transmitted since last start.
0 messages received since last start.
Filter History: Filters are open for Standard and Extended IDs.
3 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.
Configuring Properties
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 u sing the
configBusSpeed function.
1-14
Tip Configure property values before you start the channel.
1 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
CAN Communication Session
2 Change the BusSpeed property of the channel to 250000:
configBusSpeed(canch1, 250000)
3 To see the changed property value, type:
get(canch1)
MATLAB displays all properties on the configured channel as before, with the changed
. . .
BusSpeed = 250000
4 Change the bus speed of the second channel (canch2) by repeating steps
BusSpeed property value:
2and3.
Starting the Configured Channel
Start your CAN channels after you configure all properties.
1-15
1 Getting Started
1 Start the first channel:
start(canch1)
2 Start the second channel:
start(canch2)
3 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.
1-16
Filter History: Filters are open for Standard and Extended IDs.
Creating a Message Object
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 transmit a message, create a message object and pack the message with the required data.
1 Build a CAN message of ID 500 of standard type and a data length of
8bytes:
messageout = canMessage(500, false, 8)
The message object is now:
messageout =
can.Message handle
canch and receive it using canch1.To
CAN Communication Session
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 —Alogical
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.
Packing a Message
After you define the message, pack it with the required data.
1 Use the pack function to pack your message with these input parameters:
pack(messageout, 25, 0, 16, 'LittleEndian')
Here you are specifying the data valuetobe25,thestartbittobe0,the signal size to be 16, and the byte order to be little-endian format.
1-17
1 Getting Started
2 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: []
1-18
Methods, Events, Superclasses
The only field that changes after you specify the data is Data. Refer to the
pack function to understand more about the input arguments.
Transmitting a Message
After you define the message and pack it with the required data, you are ready to transmit the message. For this example, use message.
1 Use the transmit function to transmit the message, supplying the channel
and the message as input arguments:
transmit(canch1, messageout)
2 To display the channel status, type:
canch1
canch to transmit the
CAN Communication Session
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: Filters are open for Standard and Extended IDs.
In the Status section, messages transmitted since last start count increments b y 1 each time you transmit a message.
Refer to the
transmit function to understand more about the input
arguments.
Receiving a Message
After your channel is online, use the receive function to receive available messages. For this example, receive the message o n the second configured channel object,
1 Toseemessagesavailabletobereceivedonthischannel,type:
canch2
The channel status displays available messages:
.
.
.
Status: Online.
canch2.
1 messages available to RECEIVE.
1-19
1 Getting Started
0 messages transmitted since last start.
0 messages received since last start.
2 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: []
1-20
Methods, Events, Superclasses
3 To 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.
CAN Communication Session
Refer to the receive function to understand more about its input arguments.
Unpacking a Message
After your channel receives a message, specify how to unpack the message and interpre t 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 =
25
Refer to the unpack function to understand more about its input arguments.
Saving and Loading a CAN Channel
“Saving a CAN Channel Object to a MATLAB File” on page 1-21
“Loading a Saved CAN Channel” on page 1-21
Saving a CAN Channel Object to a MATLAB File
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 file
mycanch.mat,type:
save mycanch.mat canch1
canch1. TosaveittotheMATLAB
Loading a Saved CAN Channel
If you have saved a CAN channel as a MATLAB file, you can load it into a session using the above, type:
load mycanch.mat
load function. For example, to reload mycanch.mat created
1-21
1 Getting Started
The loaded CAN channel object reconnects to the specified hardware and reconfigures itself to the specifications when the channel was saved.
Performing Advanced Configurations
“Configuring Message Filtering” on page 1-22
“Configuring Multiplexing” on page 1-23
“Configuring Silent Mode” on page 1-26
Configuring Message Filtering
You can set up filters on your channel to accept messages 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:
filterAcceptRange
filterBlockRange
1-22
filterReset
filterSet
To specify a range of message IDs that you want the channel to accept, type:
stop(canch1) filterAcceptRange(canch1, 500, 625)
Now you can build a message, and then pack, transmit, receive, and unpack it. If you display your channel settings, you see the status of the message filters on it.
canch1
Summary of CAN Channel using 'Vector' 'CANcaseXL 1' Channel 1.
.
.
.
Filter History: Filters are open for Standard and Extended IDs.
Block Range added. Starting ID: 0 Ending ID: 2047
Accept Range added. Starting ID: 500 Ending ID: 625
CAN Communication Session
Configuring Multiplexing
Use multiplexing to represent multiple signals in one signal’s location in a CAN message’s data. A mult iplexed message can have three types of signals:
Standard signal
This signal is always active. You can create one or more standard signals.
Multiplexor signal
Also called the mode signal, it is always active and its value determines which multiplexed signal is currently active in the message d ata . You can create only one multiplexor signal per message.
Multiplexed s ignal
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.
1 Create a CAN database:
d = canDatabase('Mux.dbc')
Note This is an example database constructed for creating multiplex messages. To try this example, u se your own database.
2 Create a CAN message:
m = canMessage(d, 'Msg')
1-23
1 Getting Started
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, Superclasses
1-24
3 To display the signals, type:
m.Signals ans =
SigB: 0 SigA: 0
MuxSig: 0
MuxSig
two multiplexed signals are active in the message.
is the multiplexor signal, whose value determines which of the
SigA and SigB are the
multiplexed signals that are activ e in the message if their multiplex values match multiplex value of
4 If you want to make SigB active, change the value of the MuxSig to 1:
MuxSig. In the example shown, SigA is active because its current
0 matches the value of MuxSig (which is 0).
m.Signals.MuxSig = 1
To display the signals, type:
m.Signals
CAN Communication Session
ans =
SigB: 0 SigA: 0
MuxSig: 1
is now active because its multiplex value of 1 matches the current
SigB
value of
5 Change the value of MuxSig to 2:
MuxSig (which is 1).
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: 2
Always 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 m ultiplex or signal.
Refer to the canMessage function to learn more about creating messages.
1-25
1 Getting Started
Configuring Silent Mode
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
1 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
SilentMode for more information.
1-26
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
CAN Communication Session
TSEG2 = 3 NumOfSamples = 1
2 Change the SilentMode property of the channel to true:
canch1.SilentMode = true
3 To see the changed property value, type:
get(canch1)
MATLAB displays all properties on the configured channel as before, with the changed
. . . SilentMode = 1 . . .
SilentMode property value:
Disconnecting Channels and Cleaning Up
“Disconnecting the Configured Channel” on page 1-27
“Cleaning Up the MAT L AB Workspace” on page 1-28
Disconnecting the Configured Chann e l
When you no longer need to communicate with your CAN bus, disconnect the CAN channel that you configured. Use the
1 Stop the first channel:
stop(canch1)
2 Check the channel status:
canch1
MATLAB displays the channel s tatus:
stop function to disconnect.
1-27
1 Getting Started
.
.
.
Status: Offline - Waiting for START.
1 messages available to RECEIVE.
1 messages transmitted since last start.
0 messages received since last start.
3 Stop the second channel:
stop(canch2)
4 Check the channel status:
canch2
MATLAB displays the channel s tatus:
Status: Offline - Waiting for START.
0 messages available to RECEIVE.
0 messages transmitted since last start.
1 messages received since last start.
1-28
Cleaning Up the MATLAB Workspace
When you no longer need the obje cts you used, remove them from the MATLAB workspace. To remove channel objects and other variables from the MATLAB workspace, use the
1 Clear the first channel:
clear canch1
2 Clear the second channel:
clear canch2
3 Clear the CAN messages:
clear('messageout', 'messagein')
4 Clear the unpacked value:
clear function.
clear value
CAN Communication Session
1-29
1 Getting Started
Accessing the Toolbox
In this section...
“Exploring the Toolbox” on page 1-30
“Getting Help” on page 1-30
“Viewing Examples” on page 1-30
Exploring the Toolbox
You can access the Vehicle Network Toolbox from the MATLAB Command Window directly by using any Vehicle Network Toolbox function. To see a list of all the functions available, type:
help vnt
Getting Help
The toolbox functions are grouped by usage. Click a specific function for more information.
1-30
To acce ss the online documentation for the Vehicle Network Toolbox, type:
doc vnt
To access the reference page for a specific function, type:
doc function_name
Viewing Examples
To follow examples in this guide use the Vector CANcaseXL device, with the Vector XL Driver Library version 6.4 or later. The Examples index in the Help browser lists these examples.
Using a CAN Database
“Vector CANdb Support” on page 2-2
“Loading and Creating Messages Using the .dbc File” on page 2-3
“Other Uses of the CAN Database” on page 2-6
2
2 Using a CAN Database
Vector CANdb Support
The Vehicle Network Toolbox supports the use of a Vector CAN database. A
.dbc file contains definitions of CAN messages and signals.
Use the Vehicle Network Toolbox to look up me ssage and signal information and build messages using the information defined in the database file.
2-2
Loading and Creatin g Messages Using the .dbc File
Loading and Creating Messages Using the .dbc File
In this section...
“Loading the CAN Database” on page 2-3
“Creating a CAN Message” on page 2-3
“Accessing Signals in the Constructed CAN Message” on page 2-4
“Adding a Database to a CAN Channel” on page 2-4
“Updating Database Information” on page 2-5
Loading the CAN Database
To use a CANdb file, load the database into your MATLAB session. At the MATLAB command prompt, type:
db = canDatabase(’filename.dbc’)
Here db is a variable you chose for your database handle and filename.dbc is the actual file name of your CAN database. If your CAN database is not in the current working directory, type the path to the database:
db = canDatabase(’path\filename.dbc’)
Tip CAN database file names containing non-alphanumeric characters such as equal signs, ampersands, and so forth are incompatible with the Vehicle Network Toolbox. You can use periods in your database name. Rename any CAN database files with non-alphanumeric characters before you use them.
This command returns a database object that you can use to create and interpret CAN messages using information stored in the database. Refer to the
canDatabase function for more information.
Creating a CAN Message
Thisexampleshowsyouhowtocreateamessageusingadatabase constructed specifically for a demo. You can access this database in the
Toolbox > VNT > VNTDemos subfolderinyourMATLABinstallation
2-3
2 Using a CAN Database
folder. This database has a message, EngineMsg. To try this example, create messages and signals using definitions in your own database .
1 Create the CAN database object:
d = canDatabase('demoVNT_CANdbFiles.dbc')
2 Create a CAN message using the message name in the database:
message = canMessage(d, 'EngineMsg')
Accessing Signals in the Constructed CAN Message
You can access the two signals defined for the mes sag e you created in the example database,
1 To display signals in your message, type:
sig = (message.Signals)
Signals in the message are displayed as follows:
message. You can also change the values for some signals.
2-4
sig =
VehicleSpeed: 0
EngineRPM: 250
2 Change the value of the EngineRPM signal:
message.Signals.EngineRPM = 300
3 Display signal information again to see the change:
sig
sig =
VehicleSpeed: 0
EngineRPM: 300
Adding a Database to a CAN Channel
To add a database to the CAN channel canch,type:
Loading and Creatin g Messages Using the .dbc File
canch.Database = canDatabase('Mux.dbc')
For m ore information, see the Database property.
Updating Database Information
When you make changes to a database file:
1 Reload the database file into your MATLAB session using the canDatabase
function.
2 Reattach the database to messages using the attachDatabase function.
2-5
2 Using a CAN Database
Other Uses of the CAN Database
In this section...
“Viewing Message Information in the CAN Database” on page 2-6
“ViewingSignalInformationinaCANMessage”onpage2-7
“Attaching a CAN Database to Existing Messages” on page 2-7
Viewing Message Information in the CAN Database
You can get information about the definition of messages in the database, a single message by name, or a single message by ID. To get message information about all messages in the database, type:
msgInfo = messageInfo(database name)
This command returns the message structure of information about messages in the database . For example:
2-6
msgInfo =
5x1 struct array with fields:
Name Comment ID Extended Length Signals
To get information about a single message by message name, type:
msgInfo = messageInfo(database name,'message name')
This command returns information about the message as defined in the database. For example:
msgInfo = messageInfo(db, 'EngineMsg')
msgInfo =
Other Uses of the CAN Database
Name: 'EngineMsg'
Comment: ''
ID: 100
Extended: 0
Length: 8
Signals: {2x1 cell}
Here the function returns information about message with name EngineMsg in the database db. You can also use the message ID to get information about a message. For example, to view the example message given here by inputting the message ID, type:
msgInfo = messageInfo(db, 100, false)
This command provides the database name, the message ID, and a Boolean valuefortheextendedvalueoftheID.
To learn how to use it and work with the database, see the
messageInfo
function.
Viewing Signal Information in a CAN Message
You can get information about all signals in a CAN message. Provide the message name or the ID as a parameter in the command:
sigInfo = signalInfo(db, 'EngineMsg')
You can also get information about a specific signal by providing the signal name:
sigInfo = signalInfo(db, 'EngineMsg', 'EngineRPM')
To learn how to use this property and work with the database, see the
signalInfo function.
Attaching a CAN Database to Existing Messages
You can attach a .dbc file to messages and apply the message definition defined in the database. Attaching a database allows you to view the messages in their physical form and use a signal-based interaction with the message data.
2-7
2 Using a CAN Database
To attach a database to a message, type:
attachDatabase(message name, database name)
Note If your message is an array, all messages in the array are associated with the database that you attach.
You can also dissociate a message from a database so that you can view the message in its raw form. To clear the attached database from a message, type:
attachDatabase(message name, [])
Note The database gets attached even if the database does not find the specified message. Even though the database is still attached to the message, the message is displayed in its raw mode.
2-8
For more information, see the attachDatabase function.
Monitoring CAN Message Traffic
“CAN Tool” on page 3-2
“Using the CAN Tool” on page 3-6
3
3 Monitoring CAN Message Traffic
CAN Tool
In this section...
“OpeningtheCANTool”onpage3-2
“CAN Tool Fields” on page 3-2
Opening the CAN Tool
The Vehicle Network Toolbox provides a graphical user interface that displays CAN message traffic on selected CAN channels.
To open the CAN Tool, type
canTool in the MATLAB Command Window.
CAN Tool Fields
The CAN Tool is a simple interface that displays all messages received by a specific CAN channel. The tool has the following fields.
3-2
CAN Tool
Confi
Chann
Disp
Bus S
Disp chan Spe
guration
el
lays all available CAN devices and channels on your system.
peed
lays the bus speed of the selected CAN channel. You can also
ge the bus speed of a channel. See Configuring the Channel Bus
ed.
3-3
3 Monitoring CAN Message Traffic
Messages
Start
Pause
Stop
Export Messages
Show only unique messages
Click this button to view message activity on the selected channel.
Click this button to pause the display of message activity on the selected channel.
Click this button to stop displaying messages on the selected channel.
Click this button to export the current message list on the selected channel up to the latest message.
Select this check box to show the mostrecentinstanceofeachmessage received on the selected channel. If you select this check box, the tool displays a simplified version of the message traffic. In this view, you will not see messages scroll up, but each message refreshes its data with each timestamp. If you do not select this option the tool displays all instances of all messages in the order that the selected channel receives them.
3-4
Messages Table
Timestamp
Displays the time, relative to the start time, that the device receives the message. The start time when you click Start in the tool starts at 0.
ID
Displays the message ID. This field displays a number in hexadecimal format for the ID and:
Displays numbers only for standard IDs.
Appends with an x for an extended ID.
Displays an r for a remote frame.
Displays error for messages w ith error frames.
Length
Displays the length of the message in bytes.
Data
Displays the data in the message in hexadecimal format.
CAN Tool
3-5
3 Monitoring CAN Message Traffic
Using the CAN Tool
In this section...
“Viewing Messages on a Channel” on page 3-6
“Configuring the Channel Bus Speed” on page 3-6
“SavingtheMessageLogFile”onpage3-7
“Viewing Unique Messages” on page 3-7
Viewing Messages on a Channel
1 Open the CAN Tool and select the device and channel connected to your
CAN bus from the Channel list.
2 The CAN Tool defaults to the bus speed set in the device driver. You can
also configure a new bus speed. See Configuring the Channel Bus Speed
3-6
3 Click St
4 To pause the display, click Pause.
5 To stop the display, click Stop.
art.
Configuring the Channel Bus Speed
Configure the bus speed when the speed of your network differs from the default value of the channel. You require initialization access for the channel to configure the bus speed.
To configure a new bus speed:
1 Type the desired value in the Bus Speed field.
ss Enter.
2 Pre
e value you set takes effect once you start the CAN channel. If an error
Th
curs when applying the new bus speed, the value reverts to the default
oc
lue specified in the hardware.
va
Using the CAN Tool
Saving the Messa
To save a log file
Export Messages
current workin
Each time you e
CAN Log.mat
Viewing Uniq
To view the mo channel, cl messages sc each new ins
ick Show only unique messages.Inthisview,youdonotsee
of the messages currently displayed in the window, click
. The tool saves the messages in a MATLAB file in your
gdirectory.
xport the messages to a file, the CAN Tool saves them as th sequential numbering.
wi
ue Messages
st recent instance of each unique message received on the
roll up, but each message refreshes its data and timestamp with
tance.
ge Log File
VNT
3-7
3 Monitoring CAN Message Traffic
3-8
Use this feature to get a snapshot of the IDs of messages that the selected channel receives. Use this information to analyze specific messages.
When you select the Show only unique messages check box, the tool continues to receive message actively. This simplified view allows you to focus on specific messages and analyze them.
To export messages when the Show only unique messages check box is selected, click Pause and then click Export messages. You cannot save the unique message list. This operation saves the complete message log in the window.
4
Using the Vehicle Network Toolbox Block Library
“Overview” on page 4-2
“Opening the Vehicle Network Toolbox Block Library” on page 4-3
“Building Simulink Models to Transmit and Receive Messages” on page 4-5
4 Using the Vehicle Network Toolbox™ Block Library
Overview
This chapter describes how to use the Vehicle Network Toolbox block library. The library contains these blocks:
CAN Configuration — Configure the settings of a CAN device.
CAN Pack — Pack signals into a CAN message.
CAN Receive — Receive CAN messages from a CAN bus.
CAN Transmit — Transmit CAN messages to a CAN bus.
CAN Unpack —UnpacksignalsfromaCANmessage.
The Vehicle Network Toolbox block library is a tool for simulating message traffic on a CAN network, as well for usingtheCANbustosendandreceive messages. You can use blocks from the block library with blocks from other Simulink libraries to create sophisticated models.
To use the Vehicle Network Toolbox block library, you require Simulink, a tool for simulating dynamic systems. Simulink is a model definition environment. Use Simulink blocks to create a block diagram that represents the computations of your system or application. Simulink is also a model simulation environment. Run the block diagram to see how y our system behaves. If you are new to Simulink, read the Simulink Getting Started Guide in the Simulink documentation to understand its functionality better.
4-2
For more detailed i nformation about the blocks in the Vehicle Network Toolbox block library, see Block Reference.
Opening the Vehicle Network Toolbox Block Library
Opening the Vehicle Network Toolbox Block Librar y
In this section...
“Using the MATLAB Command Window” on page 4-3
“Using the Simulink Library Browser” on page 4-4
Using the MATLAB Command Window
To open the Vehicle Network Toolbox block library, enter
canlib
in the MATLAB Command Window. M ATLAB displays the contents of the library in a separate window.
4-3
4 Using the Vehicle Network Toolbox™ Block Library
Using the Simuli
To open the Vehic Browser from MAT block librarie
To start the Si
simulink
at the MATLAB The left pane listed firs the Vehicle
Communicat
t, followed by other libraries listed alphabetically under it. To open
le Network Toolbox block library, start the Simulink Library
LAB. Then select the library from the lis t of available
s displayed in the browser.
mulink Library Browser, enter
Command Window. MATLAB opens the browser window.
lists available block libraries, with the basic Simulink library
Network Toolbox block library, click its icon and select CAN
ion for the CAN blocks.
nk Library Browser
4-4
Simulink loads and displays the blocks in the library.
Building Simulink®Models to Transmit and Receive Messages
Building Simulink Models to Transmit and Receive Messages
In this section...
“Build a Message Transmit Model” on page 4-5
“Build a Message Receive Model” on page 4-10
“Save and Run the Model” on page 4-17
Build a Mess
This secti Network To example il
Use virtu
Use the CA
Use the C
Use the C
Use thi “Save a run the
“Step
“Step
“Ste
“Ste
“St
“St
on provides an example that builds a simple model using Vehicle
olbox blocks with other blocks in the Simulink library. This
lustrates how to send data via a CAN network.
al CAN channels to transmit messages.
s section with “Build a Message Receive Model” on page 4-10 and nd Run the Model” on page 4-17 to build your complete model and
simulation.
1: Open the Block Library” on page 4-5
2: Create a New Model” on page 4-6
p 3: Drag Vehicle Network Toolbox Blocks i nto the Model” on page 4-7
p 4: Drag Other Blocks to Complete the Model” on page 4-7
ep 5: Connect the Blocks” on page 4-8
ep 6: Specify the Block Parameter Values” on p age 4-8
age Transmit Model
N Configuration block to configure your CAN channels.
onstant block to send data to the CAN Pack block.
AN Transmit block to send the data to the virtual CAN channel.
Step 1: Open the Block Library
open the Vehicle Network Toolbox block library, start the Simulink Library
To
owser by entering:
Br
4-5
4 Using the Vehicle Network Toolbox™ Block Library
simulink
in the MATLAB Command Window. The left pane in the Simulink Library Browser lists the available block libraries. To open the Vehicle Network Toolbox block library, click its icon. Th en click CAN Communication to open the CAN blocks. See Using the Simulink Library Browser for more information.
Step 2: Create a New Model
To use a block, add it to an existing model or create a mo de l.
For this example, create a model by clicking the New model button on the toolbar.
4-6
Building Simulink®Models to Transmit and Receive Messages
You c an also select File>New>Modelfrom the Simulink Library Browser. Simulink opens an empty model window on the display. To name the new model, use the Save option.
Step 3: Drag Vehicle Network Toolbox Blocks into the Model
To use the blocks in a model, click a block in the library and, holding the mouse button down, drag it into the model window. For this example, you need one instance each of the CAN Configuration, CAN Pack, and CAN Tarnsmit blocks in your model.
Step 4: Drag Other Blocks to Complete the Model
This ex ample requires a source block that feeds data to the CAN Pack block. Add a Constant block to your m odel.
4-7
4 Using the Vehicle Network Toolbox™ Block Library
Step 5: Connect the Blocks
Make a connection between the Constant block and the CAN Pack block. When you move the pointer near the output port of the Constant block, the pointer becomes a cross hair. Click the Constant block output port and, holding the mouse button, drag the pointer to the input port of the CAN Pack block. Then release the button.
4-8
In the same way, make a connection between the output port of the CAN Pack block and the input port of the CAN Transmit block.
The CAN Co nfig uration block does not connect to any other block. This blo ck configures the CAN channel used by the CAN Transmit block to transmit the packed message.
Step 6: Specify the Block Parameter Values
You set parameters for the blocks in your model by double-clicking the block.
Configure the CAN Configuration Block. Double-click the CAN Configuration block to open its parameters dialog box. Set the:
Device to
Bus speed to 500000
Vector Virtual 1 (Channel 1)
Building Simulink®Models to Transmit and Receive Messages
Acknowledge Mode to Normal
Click OK.
Configure the CAN Pack Block. Double-click the CAN Pack block to open its parameters dialog box. Set the:
Data is input as to
raw data
Name to the default value CAN Msg
Identifier type to the default Standard (11-bit identifier) type
Identifier to
500
Length (bytes) to the default length of 8
Click OK.
Configure the CAN Transmit Block. Double-click the C AN Transmit block to open its parameters dialog box. Set Device to
(Channel 1)
.ClickA pply,thenOK.
Vector Virtual 1
Configure the Constant Block. Double-click the Constant block to open its parameters dialog box. O n the Main tab, set the:
Constant value to
[12345678]
Sample time to 0.01 seconds
On the Signal Attributes tab, set the Output data type to
uint8.ClickOK.
Your model looks like this figure.
4-9
4 Using the Vehicle Network Toolbox™ Block Library
4-10
Build a Message Receive Model
This section provides a n example that builds a simple model using the Vehicle Network Toolbox blocks with other blocks in the Simulink library. This example illustrates how to receive data via a CAN network.
Use a virtual CAN channel to receive messages.
Use the CAN Configuration block to configure your virtual CAN channels.
Use the CAN Receive block to receive the message sent by the blocks built
in “Build a Message Transmit Model” on page 4-5.
Use a Function–Call Subsystem block that contains the CAN Unpack block.
This function takes in the data from the CAN Receive block and uses the parameters of the CAN Unpack block to unpack your message data.
Use a Scope block to show the transfer of data visually.
Building Simulink®Models to Transmit and Receive Messages
Use this section with “Build a Mess ag e Transmit Model” on page 4-5 and “Save and Run the Model” on page 4-17 to build your complete model and run the simulation.
“Step 7: Drag Vehicle Network Toolbox Blocks into the Model” on page 4-11
“Step 8: Drag Other Blocks to Complete the Model” on page 4-12
“Step 9: Connect the Blocks” on page 4-14
“Step 10: Specify the Block Parameter Values” on page 4-16
Step 7: Drag Vehicle Network Toolbox Blocks into the Model
For this example, you need one instance each of the CAN Configuration, CAN Receive, and CAN Unpack blocks in your model. However, you add only the CAN Configuration and the CAN Receive blocks here. Add the CAN Unpack block into the Function–Call Subsystem described in “Step 8: Drag Other Blocks to Complete the Model” on page 4-12.
Tip Configure a separate CAN channel for the CAN Receive and CAN Transmit blocks.
4-11
4 Using the Vehicle Network Toolbox™ Block Library
Step 8: Drag Other Blocks to Complete the Model
Use the Function–Call Subsystem block from the Simulink Ports & Subsystems block library to build your CAN Message pack subsystem.
1 Drag the Function–Call Subsystem block into the model.
4-12
2 Double-click the Function–Call Subsystem block to open the subsystem
model.
Building Simulink®Models to Transmit and Receive Messages
3 Drop the C
library i
n this subsystem.
AN Unpack block from the Vehicle Network Toolbox block
4-13
4 Using the Vehicle Network Toolbox™ Block Library
To see the results of the simulation visually, drag the Scope block from the Simulink block library into your model.
4-14
Step 9: Connect the Blocks
1 Connect the CAN Msg output port on the CAN Receive b lock to the In1
input port on the Function–Call Subsystem block.
2 Open the Function–Call Subsystem block and:
Double-click In1 to rename it to
Double-click Out1 to rename it to
3 Rename the Function–Call Subsystem block to CAN Unpack Subsystem.
4 Connect the f() output port on the CAN Receive block to the function()
input port on the Function–Call Subsystem block.
CAN Msg.
data.
Building Simulink®Models to Transmit and Receive Messages
5 Connect the CAN Unpack Subsystem output port to the input port on the
Scope block.
Your model looks like this figure.
4-15
4 Using the Vehicle Network Toolbox™ Block Library
The CAN Configuration block does not connect to any other block. This block co nfigures the CAN channel used by the CAN Receive block to receive the CAN message.
Step 10: Specify the Block Parameter Values
Set parameters for the blocks in your model by double- clicking the block.
Configure the CAN Con figuration1 Block. Double -cli ck the CAN Configuration block to open its parameters dialog box. Set the:
Device to
Bus speed to 500000
Acknowledge Mode to Normal
Click OK.
Configure the CAN Receive Block. Double-click the CAN Receive block to open its Parameters dialog box. Set the:
Device to
Sample time to 0.01
Number of m essages received at each timestep to All
Click OK.
Configure the CAN U npack Subsystem. Double-click the CAN Unpack subsystem to open the F unction–Call Subsystem model. In the model, double-click the CAN Unpack block to open its parameters dialog box. Set the:
Data to be output as to
Name to the default value CAN Msg
Identifier type to the default Standard (11-bit identifier) type
Vector Virtual 1 (Channel 2)
Vector Virtual 1 (Channel 2)
raw data
4-16
Identifier to
Length (bytes) to the default length of 8
500
Building Simulink®Models to Transmit and Receive Messages
Click OK.
Your subsystem looks like this figure.
Save and Run the Model
This section shows you how to save the models you built, “Build a Message Transmit Model” on page 4-5 and “Build a Message Receive Model” on page 4-10.
“Step 11: Save the Model” on page 4-17
“Step 12: Change Configuration Parameters” on page 4-18
“Step 13: Run the Simulation” on page 4-18
“Step 14: View the Results” on page 4-19
Step 11: Save the Model
Before you run the simulation, save your model by clicking the Save icon or selecting File > Save from the menu bar.
4-17
4 Using the Vehicle Network Toolbox™ Block Library
Step 12: Change Configuration Parameters
1 In your model window, select Simulation > Configuration Parameters.
The Configuration Parameters dialog box opens.
2 In the Solver Options section, select:
Fixed-step from the Type list.
Discrete (no continuous states) from the Solver list.
Step 13: Run the Simulation
To run the simulation, click the Start button on the model window toolbar. Alternatively, you can use the Simulation menu in the model window and choose the Start option.
When you run the simulation, the CAN Transmit block gets the message from the CAN Pack block. It then transmits it via Virtual Channel 1. The CAN Receive b lock on V irtual Channel 2 receives this message and hands it to the CAN Unpack block to unpack the message.
4-18
While the simulation is running, the status bar at the bottom of the model window updates the progress of the simulation.
Building Simulink®Models to Transmit and Receive Messages
Step 14: View the Results
Double
-clicktheScopeblocktoviewthemessagetransferonagraph.
4-19
4 Using the Vehicle Network Toolbox™ Block Library
If you cannot see all the data on the graph, click the Autoscale toolbar button, which automatically scales both axes to display all stored simulation data.
4-20
In the graph, the horizontal axis represents the simulation time in seconds and the vertical axis represents the received data value. In the Message Transmit model, you configured blocks to pack and transm it an array of constant values, [1 2 3 4 5 6 7 8], every 0.01 second of simulation time. In the Message Receive model, these values are received and unpacked. The output in the Scope window represents the received data values.
Function Reference
5
CAN Channel Construction (p. 5-2)
CAN Channel Configuration (p. 5-3) Functions related to configuring
CAN Channel Execution (p. 5-4)
CAN Channel Status (p. 5-5)
CAN Database (p. 5-6) Functions related to CAN database
CAN Message Handling (p. 5-7)
CAN Message Filtering (p. 5-8) Functions related to setting up C AN
Information and Help (p. 5-9)
Graphical Tools (p. 5-10) Functions related to CAN Tools
Vector Informatik (p. 5-11) Functions specifically related to
Functions related to constructing CAN channel
CAN channel
Functions related to executing configured CAN channel.
Functions related to checking and modifying CAN channel status
Functions related to working with CAN messages
message filters
Functions related to displaying help information
Vector hardware functionality
5 Function Reference
CAN Channel Construction
canChannel
Construct CAN channel connected to selected device
5-2
CAN Channel Configuration
CAN Channel Configuration
get
set
Return property values
Configure property values
5-3
5 Function Reference
CAN Channel Execution
receive
receiveRaw
replay
start
stop
transmit
Receive messages from CA N bus
Receive raw messages from CA N bus
Retransmit messages from CAN bus
Set CAN channel online
Set CAN channel offline
Send CAN messages to CAN bus
5-4
CAN Channel Status
CAN Channel Status
configBusSpeed
Set bit timing rate of CAN channel
5-5
5 Function Reference
CAN Database
canDatabase
messageInfo
signalInfo
Create handle to CAN database file
Information about CAN messages
Information about signals in CAN message
5-6
CAN Message Handling
CAN Message Handling
attachDatabase
canMessage
canMessageCompatibilityMode
extractAll
extractRecent
extractTime
pack
unpack
Attach CAN database to messages and remove CAN database from messages
Build CAN message based on user-specified structure
Enable dynamic signal property support
Select all instances of message from array of messages
Select most recent message from array of messages
Select messages occurring within specified time range from arra y of messages
Pack signal data into CAN message
Unpack signal data from message
5-7
5 Function Reference
CAN Message Filtering
filterReset
filterSet
Open CAN message acceptance filters
Set specific CAN message acceptance filter configuration
5-8
Information and Help
Information and Help
canHWInfo
canSupport
Information on available CAN devices
Generate technical support log
5-9
5 Function Reference
Graphical Tools
canTool
Open CAN Tool
5-10
Vector Informatik
Vect o r Informatik
filterAcceptRange
filterBlockRange
Set range of CAN identif iers to pass acceptance filter
Set range of CAN identifiers to block via acceptance filter
5-11
5 Function Reference
5-12
Functions — Alphabetical List
6
attachDatabase
Purpose Attach CAN database to messages and remove CAN database from
messages
Syntax attachDatabase (message, database)
attachDatabase (message, [])
Arguments
message
database
ThenameoftheCANmessagethatyou want to attach the database to or remove the database from.
The name of the database (.dbc file) that youwanttoattachtothemessageor remove from the message.
Description attachDatabase (message, database) attaches the specified
database to the specified message. You can then use signal-based interaction with the message data, interpreting the message in its physical form.
attachDatabase (message, []) removes any attached database from
the specified message. You can then interpret messages in their raw form.
Remarks If the specified message is an array, then the database attaches itself
to each entry in the array. The database attaches itself to the message even if the message you specified does not exist in the database. The message then appears and operates like a raw message. To attach the database to the CAN channel directly, edit the Database p roperty of the channel object.
Examples candb = canDatabase('C:\Database.dbc')
message = receive(canch, Inf) attachDatabase(message, candb)
See Also canDatabase, receive
6-2
canChannel
Purpose Construct CAN channel connected to selected device
Syntax canch = canChannel('vendor', 'device', devicechannelindex)
Arguments
vendor
device
devicechannelindex
canch
ThenameoftheCANdevicevendor. Specify the vendor name as a string.
The CAN interface that you want to connect to.
A numeric channel on the specified device.
The CAN channel object the you create.
Description canch = canChannel('vendor', 'device', devicechannelindex)
returns a CAN channel connected to a device from a specified ve nd o r.
ForVectorproducts, device index, such as CANcardXL devices,
canHWInfo to obtain a list of available devices.
Use
device is a combination of the device type and a
'CANCaseXL 1'. For example, if there are two
device can be 'CANcardXL 1' or 'CANcardXL 2'.
Remarks The Vehicle Network Toolbox currently supports Vector and Kvaser
devices. Refer to the Supported Hardware topic.
6-3
canChannel
Examples canch = canChannel('Vector','CANCaseXL 1',1)
canch = canChannel('Vector','Virtual 1',2)
Notes Youcannotusethesamevariabletocreatemultiplechannels sequentially. Clear any channel in use before using the same variable to construct a new CAN channel.
You cannot create arrays of CAN channel objects. Each object you create m ust exist as its own individual variable.
See Also canHWInfo
6-4
canDatabase
Purpose Create handle to CAN database file
Syntax candb = canDatabase('dbfile.dbc')
Description candb = canDatabase('dbfile.dbc') creates a handle to the specified
database file or a relative path. MATLAB looks for path. Vehicle Network Toolbox supports the Vector CAN database (
.dbc)files.
Examples candb = canDatabase('C:\Database.dbc')
See Also canMessage
dbfile.dbc. You can specify just a file name, a f ull path,
dbfile.dbc on the MATLAB
6-5
canHWInfo
Purpose Information on available CAN devices
Syntax out = canHWInfo()
Description out = canHWInfo() returns information about CAN devices and
displays the information on a per vendor and channel basis. Use the output of
Examples info = canHWInfo()
get(info)
See Also canChannel
canHWInfo to obtain more detailed results.
ToolboxName: 'Vehicle Network Toolbox'
ToolboxVersion: '1.0 (R2009a)'
MATLABVersion: '7.8 (R2009a)'
VendorInfo: [1x1 can.vector.VendorInfo]
get on
6-6
Purpose Build CAN message based on user-specified structure
Syntax message = canMessage(id, extended, datalength)
message = canMessage(database, messagename)
canMessage
Arguments
id
extended
datalength
database
messagename
message
The ID of the message that you specify.
Indicates whether the message ID is of standard or extended type. The B oolean value is or
false if standard.
The length of the data of the message, in bytes. Specify from
Handle to the CAN database containing the message definition.
Thenameofthemessagedefinitioninthedatabase.
The message object returned from the function.
0 through 8.
true if extended
Description message = canMessage(id, extended, datalength) creates and
returns a CAN mes sage object, from the raw message information.
message = canMessage(database, messagename) constructs a
message using the message definition of the specified message, in the specified database.
Examples To construct a CAN message, type:
message = canMessage(2500, true, 4)
To construct a message using CAN database message definitions, create a database object using the your message:
candb = ('c:\database.dbc') message = canMessage (candb, 'messagename')
canDatabase function, and then construct
6-7
canMessage
See Also attachDatabase, canDatabase, extractAll, extractRecent,
extractTime, pack, unpack
6-8
canMessageCompatibilityMode
Purpose Enable dynamic signal property support
Note canMessageCompatibilityMode will be removed in a future
version.
Syntax canMessageCompatibilityMode(mode)
mode = canMessageCompatibilityMode()
Arguments
mode
Indicates if the compatibility mode is on (allows access to dynamic signals) or off (access signals via the
Signals property). The Boolean value for mode
is true if compatibility mode is o n and false if it is off. By default the mode is
false.
Description canMessageCompatibilityMode(mode) restores or removes access to
dynamic signal properties for CAN messages based on your input. Ifyoucannotupdateyourcodetousethenew this time, enter update your code and use the new significant performance increase over the use of dynamic properties.
mode = canMessageCompatibilityMode() queries the current state of
the CAN message compatibility mode.
The compatibility mode is false by default. Change the mode each time you start a new MATLAB session. Set the mode value to compatibility m ode on and
Note If mode is 0 (false), then you cannot access dynamic signals and must use the
true as your mode value. It is recommended that you
Signals property, which provides a
false to turn it off.
Signals property.
Signals property at
true to turn
6-9
canMessageCompatibilityMode
Examples % To query current state of CAN message compatibility mode:
mode = canMessageCompatibilityMode()
% To enable dynamic signal property support: canMessageCompatibilityMode(true)
See Also Signals
6-10
canSupport
Purpose Generate technical support log
Syntax canSupport()
Description canSupport() returns diagnostic information for all installed CAN
devicesandsavesoutputtothetextfile working directory.
For online support of Vehicle Network Toolbox software, visit the toolbox page on the MathWorks Web site.
cansupport.txt in the current
6-11
canTool
Purpose Open CAN Tool
Syntax canTool
Description canTool starts the CAN Tool, which displays live CAN message traffic.
Use the CAN Tool to view message traffic using a se lected CAN device and channel. You can also export messages to a log file via this tool.
For more information about this tool, refer to Chapter 3, “Monitoring CAN Message Traffic”.
6-12
Purpose Set bit timing rate of CAN channel
Syntax configBusSpeed(canch, busspeed)
configBusSpeed(canch, busspeed, sjw, tseg1, tseg2,
numberofsamples)
configBusSpeed
Arguments
canch
busspeed
sjw
tseg1
tseg2
numberofsamples
The CAN channel object that you want to set the bit timing rate for.
The user-specified bit timing rate for the specified object.
The synchronization jump width. This value is the maximum value of time bit adjustments.
Thelengthoftimeatthestartofthesamplepoint within a bit time.
The length of time at the end of the sample point within a bit time.
The specified count of bit samples used.
Description configBusSpeed(canch, busspeed) sets the spe ed of the CAN channel
in a direct form that uses baseline bit timing calculation factors.
configBusSpeed(canch, busspeed, sjw, tseg1, tseg2, numberofsamples) busspeed using the specified bit timing calculation factors to control
thetiminginanadvancedform.
sets the speed of the CAN channel canch to
Remarks Unless you have specific tim ing re quirements for your CAN connection,
use the direct form of bus speed only when the CAN channel is offline. The channel must also have initialization access to the CAN device.
configBusSpeed. Also note that you can set the
Synchronize all nodes on the network for CAN to work successfully. However, over time, clocks on different nodes will get out of sync, and must resynchronize.
SJW specifies the maximum width (in time) that
6-13
configBusSpeed
you can add to tseg1 (in a slow er transmitter), or subtract from tseg2 (in a faster transmitter) to regain synchronization during the receipt of a CAN message.
Examples To configure the bus speed using baseline bit timing calculation, type:
canch = canChannel('Vector','CANCaseXL 1',1) configBusSpeed(canch,250000)
To specify th e bit timing calculations, type:
canch = canChannel('Kvaser', 'USBcan Professional 1', 1) configBusSpeed(channel, 500000, 1, 4, 3, 1)
See Also canChannel
6-14
extractAll
Purpose Select all instances of message from array of messages
Syntax [extracted, remainder] = extractAll(message, messagename)
[extracted, remainder] = extractAll(message, id, extended)
Arguments
message
messagename
id
extended
extracted
remainder
An array of C AN message objects that you specify to parse and find the specified messages by name or ID.
Thenameofthemessagethatyouspecifyto extract.
The ID of the message that you specify to extract.
Indicates whether the message ID is a standard or extended type. The Boolean value is extended and
An array of CAN message objects returned with all instances of
A CAN message object containing all messages in the original inpu t
id removed.
false if standard.
id found in the message.
message with all instances of
true if
Description [extracted, remainder] = extractAll(message, messagename)
parses the given array message, and returns all instances of messages matching the specified message name.
[extracted, remainder] = extractAll(message, id, extended)
parses the given array message, and returns all instances of messages matching the specified ID with the specified standard or extended type.
Remarks You can specify id as a cell array of message names or a vector of
identifiers. For example, if you pass
extractAll returns every instance of both CAN message 250 and
message
5000 that it finds in the message array. If any id in the vector
id in as [250 5000], [false true],
6-15
extractAll
is an extended type, set extended to true and as a vector of the same length as
Examples [msgOut, remainder]=extractAll(message, 'msg1')
[msgOut, remander]=extractAll(message,{'msg1' 'msg2' 'msg3'})
[msgOut, remainder]=extractAll(message, 3000, true)
[msgOut, remainder]=extractAll(message,[200 5000],[false true])
See Also extractRecent, extractTime
id.
6-16
Loading...