Setting up CAN on Raspberry Pi
Last updated
Last updated
The easiest way to work with CAN bus in Linux is the program set. Install it with the following command:
Can-utils consists of the following tools:
candump - allows to print, filter and record all data that is being received by a CAN interface
canplayer - playbacks recorded frames
cansend - transmits CAN frame
cangen - generates random CAN frames
canbusload - displays current CAN bus load
We will mainly use the candump and cansend utilities.
To start the CAN interface, enter the command
The bitrate field specifies interface speed, 1000000 bit/s in this example.
In case of "Cannot find device "can0"" error, do the following:
Append the string
Save (Ctrl+S) and close (Ctrl+X) the file. Reboot the raspberry:
To view frames on the CAN0 bus use the candump command
This will print all frames. In case you want to see frames with specific ID, use the command
candump can0,<ID>:7ff
. It uses hexadecimal numerals. ID=100 decimal will be ID=0x64 hexadecimal (100=0х64). For this ID the command takes the following form:
To send frames to the bus use cansend. Sending 4 bytes (0xDE 0xAD 0xBE 0xEF) with message ID=100(0x64) looks like this:
To disable the interface use
CAN FD is the second generation of CAN protocol developed by Bosch. The basic idea is to overclock part of the frame and to oversize the payload. Developed in 2011 and released in 2012 by Bosch, CAN FD was developed to meet the need to increase the data transfer rate up to 5 times faster and with larger frame/message sizes. To configure CAN interface with FD mode on, use the following command:
In addition to bitrate there's dbitrate which specifies the speed of data segment in frame.
From here on we will use FD mode by default.
Let's set up automatic CAN bus configuration when Raspberry starts. To do so we will write a little script canup.sh and place it in home directory
To make the file executable:
To launch application when Raspberry starts you have to specify it in /etc/rc.local
In the nano editor window you will see lines of code. Find the exit 0
line and put the following command before it:
Save (Ctrl + S) and close (Ctrl + X) the editor. Reboot the Raspberry
It is useful to know the command
This command allows you to get information about the CAN0 interface. Note that if there are no errors when sending or receiving messages, you will see 0 in the error counter, as shown below