Main Content

Get Started with SocketCAN Devices

This example shows you how to identify, set up, and configure SocketCAN devices in a Linux® terminal, then access them from MATLAB® using Vehicle Network Toolbox™.

Configuring SocketCAN devices requires system (sudo) privileges. This example uses two SocketCAN supported CAN/CAN FD devices (can0 and can1) connected in loopback mode.

Identify SocketCAN Devices on a Linux System

For a SocketCAN native interface associated with CAN/CAN FD, hardware devices register them as can0, can1, can2, etc., with the Linux network layer. When you plug a SocketCAN device into a Linux system, the Linux kernel loads a corresponding device driver and the Linux network layer creates the CAN network interface corresponding to the device (e.g., can0).

To see the list of available SocketCAN/CAN FD supported hardware devices on your system, run the following command in a Linux terminal:

ip -details link show type can

This lists all the supported hardware CAN/CAN FD devices on your system:

% ip -details link show type can
7: can0: <NOARP,ECHO> mtu 16 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 10
    link/can  promiscuity 0 minmtu 0 maxmtu 0 
    can state STOPPED (berr-counter tx 0 rx 0) restart-ms 0 
	  bitrate 500000 sample-point 0.875 
	  tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 1
	  pcan_usb_pro_fd: tseg1 1..256 tseg2 1..128 sjw 1..128 brp 1..1024 brp-inc 1
	  pcan_usb_pro_fd: dtseg1 1..32 dtseg2 1..16 dsjw 1..16 dbrp 1..1024 dbrp-inc 1
	  clock 80000000 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 
8: can1: <NOARP,ECHO> mtu 16 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 10
    link/can  promiscuity 0 minmtu 0 maxmtu 0 
    can state STOPPED (berr-counter tx 0 rx 0) restart-ms 0 
	  bitrate 500000 sample-point 0.875 
	  tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 1
	  pcan_usb_pro_fd: tseg1 1..256 tseg2 1..128 sjw 1..128 brp 1..1024 brp-inc 1
	  pcan_usb_pro_fd: dtseg1 1..32 dtseg2 1..16 dsjw 1..16 dbrp 1..1024 dbrp-inc 1
	  clock 80000000 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535

Your output might be different depending on number of network device connected and type of CAN devices.

If a connected device does not appear, the device might not be detected by the Linux network layer and needs a device specific CAN module to be loaded for the vendor. You can use the modprobe command to load vendor-specific CAN modules. For example, to load the Kvaser CAN module, run % sudo modprobe kvaser_usb. If you are still unable to list connected CAN devices, contact your device vendor for help.

Configure SocketCAN Devices

After you have identified CAN devices to use with SocketCAN, you can configure those devices based on your requirements. The standard CAN and CAN FD device setups are listed here.

To set up the can0 device for CAN communication:

sudo ip link set can0 type can bitrate 500000

To set up the can1 device for CAN FD communication:

sudo ip link set can1 type can bitrate 500000 sample-point 0.75 dbitrate 4000000 dsample-point 0.8 fd on

During device configuration, you can also modify other parameters shown in the SocketCAN - Controller Area Network page.

Create Virtual SocketCAN Devices (optional)

You can also create virtual channels with SocketCAN. Create a virtual SocketCAN channel vcan0.

sudo ip link add dev vcan0 type vcan

To visualize available SocketCAN virtual interfaces for CAN/CAN FD support, run the following command:

ip -details link show type vcan

Bring Configured Devices Online

MATLAB and Simulink® can list only those SocketCAN devices that are properly configured and brought online. Bring configured hardware devices online.

sudo ip link set up can0
sudo ip link set up can1

Bring configured virtual device online.

sudo ip link set up vcan0

Communicate with SocketCAN Devices

When your SocketCAN devices are set up and brought online, you can use them with MATLAB and Simulink for CAN communication in the same way as any other CAN/CAN FD supported devices.

To visualize correctly configured SocketCAN devices, call canChannelList in MATLAB.

canChannelList
ans=5×6 table
      Vendor         Device       Channel    DeviceModel    ProtocolMode     SerialNumber
    ___________    ___________    _______    ___________    _____________    ____________

    "MathWorks"    "Virtual 1"        1       "Virtual"     "CAN, CAN FD"        "0"     
    "MathWorks"    "Virtual 1"        2       "Virtual"     "CAN, CAN FD"        "0"     
    "SocketCAN"    "can0"           NaN       ""            "CAN"                "0"     
    "SocketCAN"    "can1"           NaN       ""            "CAN, CAN FD"        "0"     
    "SocketCAN"    "vcan0"          NaN       "Virtual"     "CAN, CAN FD"        "0"     

canFDChannelList
ans=4×6 table
      Vendor         Device       Channel    DeviceModel    ProtocolMode     SerialNumber
    ___________    ___________    _______    ___________    _____________    ____________

    "MathWorks"    "Virtual 1"        1       "Virtual"     "CAN, CAN FD"        "0"     
    "MathWorks"    "Virtual 1"        2       "Virtual"     "CAN, CAN FD"        "0"     
    "SocketCAN"    "can1"           NaN       ""            "CAN, CAN FD"        "0"     
    "SocketCAN"    "vcan0"          NaN       "Virtual"     "CAN, CAN FD"        "0"     

Create a CAN channel using canChannel to transmit and receive CAN messages by specifying the vendor name as SocketCAN and device names as can0 and can1.

ch1 = canChannel('SocketCAN','can0')
ch1 = 
  Channel with properties:

   Device Information
           DeviceVendor: 'SocketCAN'
                 Device: 'can0'
           ProtocolMode: 'CAN'

   Status Information
                Running: 0
      MessagesAvailable: 0
       MessagesReceived: 0
    MessagesTransmitted: 0
       InitialTimestamp: [0×0 datetime]
          FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All'

   Channel Information
              BusStatus: 'ERROR-ACTIVE'
      ReceiveErrorCount: 0
     TransmitErrorCount: 0
               BusSpeed: 500000

   Other Information
               Database: []
               UserData: []

ch2 = canChannel('SocketCAN','can1')
ch2 = 
  Channel with properties:

   Device Information
           DeviceVendor: 'SocketCAN'
                 Device: 'can1'
           ProtocolMode: 'CAN'

   Status Information
                Running: 0
      MessagesAvailable: 0
       MessagesReceived: 0
    MessagesTransmitted: 0
       InitialTimestamp: [0×0 datetime]
          FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All'

   Channel Information
              BusStatus: 'ERROR-ACTIVE'
      ReceiveErrorCount: 0
     TransmitErrorCount: 0
               BusSpeed: 500000

   Other Information
               Database: []
               UserData: []

Create a CAN message using canMessage to transmit.

message = canMessage(250, false, 8);
message.Data = ([45 213 53 1 3 213 123 43]);

Use the start command to set channels online.

start(ch1);
start(ch2);

In this case, the can0 and can1 hardware devices are connected in a loopback mode, transmitting on ch1 using the transmit function.

transmit(ch1,message);

Receive available messages from the channel using the receive function.

rxMsg = receive(ch2,Inf,"OutputFormat","timetable");
head(rxMsg)
       Time       ID     Extended       Name                   Data                Length      Signals       Error    Remote
    __________    ___    ________    __________    ____________________________    ______    ____________    _____    ______

    2.2614 sec    250     false      {0×0 char}    {[45 213 53 1 3 213 123 43]}      8       {0×0 struct}    false    false 

Set the channels offline.

stop(ch1);
stop(ch2);

Bring Down Online Devices

When done with your SocketCAN devices, bring down the online devices in a Linux terminal.

sudo ip link set down can0
sudo ip link set down can1
sudo ip link set down vcan0

During MATLAB execution, if you want to change any CAN device parameters, bring down the device, change the parameters, and bring the device online again. This also resets the CAN device.