Table of Contents
本人最早在06、07年开始搞CAN总线,采用的是RM9200+SJA1000和LPC2100通信。
当时CAN有CANOpen和DeviceNet 2种架构之分。我们采用了开源的lincan-0.3.2,把CAN注册为一个char设备,然后通过read/write函数进行CAN报文的接收和发送。
最近玩了freescale的i.MX6UL,这颗CPU本身具备2路CAN总线。
查了下当前CAN的支持,发现从2.6.25开始,CAN已经被引入到linux内核中,并被作为一个socket设备进行管理。
工具
由于CAN被整合进network,所以需要新的ip才能支持,点击进官网。或者可以使用GIT同步代码:
1 2 3 |
$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/shemminger/iproute2.git |
常用的CAN命令
查看可设置的配置参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$ ip link set can0 type can help Usage: ip link set DEVICE type can [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] | [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1 phase-seg2 PHASE-SEG2 [ sjw SJW ] ] [ loopback { on | off } ] [ listen-only { on | off } ] [ triple-sampling { on | off } ] [ restart-ms TIME-MS ] [ restart ] Where: BITRATE := { 1..1000000 } SAMPLE-POINT := { 0.000..0.999 } TQ := { NUMBER } PROP-SEG := { 1..8 } PHASE-SEG1 := { 1..8 } PHASE-SEG2 := { 1..8 } SJW := { 1..4 } RESTART-MS := { 0 | NUMBER } |
设置CAN波特率为1Mbps:
1 2 3 |
$ ip link set can0 up type can bitrate 1000000 |
查看CAN的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ ip -s -d link show can0 2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UNKNOWN mode DEFAULT group default qlen 10 link/can promiscuity 0 can state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0 bitrate 1000000 sample-point 0.733 tq 66 prop-seg 5 phase-seg1 5 phase-seg2 4 sjw 1 flexcan: tseg1 4..16 tseg2 2..8 sjw 1..4 brp 1..256 brp-inc 1 clock 30000000 re-started bus-errors arbit-lost error-warn error-pass bus-off 0 0 0 1 0 0 RX: bytes packets errors dropped overrun mcast 44427 7830 0 0 0 0 TX: bytes packets errors dropped carrier collsns 29 29 0 0 0 0 |
启动/停止CAN:
1 2 3 |
$ ip link set can0 up/down |
或者
1 2 3 |
$ ifconfig can0 up/down |
接收CAN报文:
1 2 3 |
$ candump can0 |
发送CAN报文
1 2 3 |
$ cansend <device> <can_frame> |
例如使用通道CAN1发送CAN ID为1,带有5个数据(0x01 0x23 0x45 0x67 0x89)的报文:
1 2 3 |
$ cansend can1 001#0123456789 |
发送远程请求帧:
1 2 3 |
$ cansend can1 500#R |
如果对方使用candump接收,则会显示:
1 2 3 4 5 |
$ candump can0 can0 001 [5] 01 23 45 67 89 can0 500 [0] remote request |
发送
参考
- https://en.wikipedia.org/wiki/SocketCAN
- Linux/Documentation/networking/can.txt
- https://github.com/linux-can/can-utils/