Vehicle Network Communication Examples

Prerequisites

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.

Discover Installed Hardware

  1. 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.
  2. Save the vector device information to a variable.

    vector = info.VendorInfo(1)        
    
  3. Get details about the first available CAN channel.

    vector.ChannelInfo(1)      
    Package: can.vector
    
      Properties:
                    Device: 'CANcaseXL 1'
        DeviceChannelIndex: 1
        DeviceSerialNumber: 24365
         ObjectConstructor: 'canChannel('Vector','CANcaseXL 1',1)'

Create a CAN Channel

    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.
    
                  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.
    
  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.

Configure 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 using the configBusSpeed function.

    Tip   Configure property values before you start the channel.

  1. Change the BusSpeed property of the channel to 250000:

    configBusSpeed(canch1, 250000)
  2. To see the changed property value, type:

    canch1.BusSpeed

    MATLAB displays all properties on the configured channel as before, with the changed BusSpeed property value:

    .
    .
    .
    	BusSpeed = 250000
  3. Change the bus speed of the second channel (canch2) by repeating steps 2 and 3.

Start the Channel

Start your CAN channels after you configure all properties.

  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.
    
          Filter History:  Standard ID Filter: Allow All | Extended ID Filter: Allow All.

Create a Message

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.

  1. 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 Message Database for more information.

Pack 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 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.

  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: []
    
      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.

Transmit 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 canch to transmit the 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 

    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.

Receive a Message

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.

  1. 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.
  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: []
    
      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.

Refer to the receive function to understand more about its input arguments.

Unpack a Message

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 =

    25

Refer to the unpack function to understand more about its input arguments.

Save a CAN Channel

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

Load a Saved Channel

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.

Filter Messages

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:

To specify message names you want to filter, create a CAN channel and attach a database to the channel:

canch1 = canChannel('Vector','CANcaseXL 1',1);
canch1.Database = canDatabase('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 All

If you start the channel and receive messages, you should now only see the EngineMsg pass through the filter.

Multiplex Signals

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:

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 data. You can create only one multiplexor signal per message.

Multiplexed signal

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, use your own database.

  2. 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, Superclasses
  3. To display the signals, type:

    m.Signals
    
    ans = 
    
          SigB: 0
          SigA: 0
        MuxSig: 0

    MuxSig 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).

  4. 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: 1

    SigB is now active because its multiplex value of 1 matches the current value of MuxSig (which is 1).

  5. 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: 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 multiplexor signal.

Refer to the canMessage function to learn more about creating messages.

Configure 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 SilentMode for more information.

  1. Change the SilentMode property of the first CAN channel, canch1 to true:

    canch.SilentMode = true
  2. To see the changed property value, type:

    canch1.SilentMode

    MATLAB displays the changed SilentMode property value:

    ans =
    
         1

Disconnect Channels and Clean Up

Disconnecting the Configured Channel

When you no longer need to communicate with your CAN bus, disconnect the CAN channel that you configured. Use the stop function to disconnect.

  1. Stop the first channel:

    stop(canch1)
    
  2. 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.
  3. Stop the second channel:

    stop(canch2)
    
  4. 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.

Clean Up the MATLAB Workspace

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.

  1. Clear the first channel:

    clear canch1
  2. Clear the second channel:

    clear canch2
  3. Clear the CAN messages:

    clear 'messageout'
    clear 'messagein'
  4. Clear the unpacked value:

    clear value
Was this topic helpful?