CAN Bus in Linux

Bring up CAN interface

Note that the maximum bitrate depends on your specific hardware, for example PiCAN2 supports up to 1Mbps.

$ sudo ip link set can0 up type can bitrate 1000000

To automatically bring up the interface during boot, you can modify “/etc/network/interfaces”

$ sudo nano /etc/network/interfaces

Add the following lines

auto can0
  iface can0 inet manual
  pre-up /sbin/ip link set can0 type can bitrate 1000000
  up /sbin/ifconfig can0 up
  down /sbin/ifconfig can0 down

You can check if CAN is brought up by using command “ifconfig”. You should see something similar to this

$ can0: flags=193<UP,RUNNING,NOARP>  mtu 16
$     unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 10  (UNSPEC)
$     RX packets 4  bytes 32 (32.0 B)
$     RX errors 0  dropped 0  overruns 0  frame 0
$     TX packets 4  bytes 32 (32.0 B)
$     TX errors 1  dropped 1 overruns 0  carrier 1  collisions 0
  1. Loopback test

You can use the loopback mode to test if PiCAN2 is working properly. You need to enable the loopback mode first.

$ sudo ip link set can0 down
$ sudo ip link set can0 type can loopback on
$ sudo ip link set can0 up type can bitrate 1000000

Now open two terminals, one as sender and one as receiver.

In sender terminal:

$ cansend can0 001#1122334455667788

In receiver terminal:

$ candump can0

If successful, you should expect

$ candump can0
$ can0  001   [8]  11 22 33 44 55 66 77 88
$ can0  001   [8]  11 22 33 44 55 66 77 88

Turn off the loopback mode:

$ sudo ip link set can0 down
$ sudo ip link set can0 type can loopback off
$ sudo ip link set can0 up type can bitrate 1000000
  1. Log can frames and playback

You can log can frames from a CAN interface to a file for debugging

$ candump -l can0

Then you can playback the log file

$ canplayer -I <candump-log-file-name>.log
  1. Dump CAN frames with filter mask

Dump can frames with filter

$ candump can0,<interested-can-id(s)>:<filter-mask>

Example:

$ candump can0,602:1fffffff

The example command dumps CAN message with ID 0x602 from can0. If you wang to dump all messages with ID 0x60x, you can adjust the filter to be 1ffffff0.

  1. More commands

Use this command to find more information of CAN related commands

$ ip link set can0 up type can help

Reference