前段时间,由于项目需要,产品中需要多增加一路CAN总线接口。CAN总线方案是ATMEL ARM9 + MCP2515。
此前已经有两路CAN总线接口了。以我对linux MCP2515驱动的熟悉,增加一路CAN总线接口的驱动不是难事。另人意外的是,在应用层的使用上,居然碰到了点意外。主要是关于bit-timing not yet defined错误。记录如下。
添加了一个CAN接口(即CAN2)
使用ifconfig查看CAN2,如下图所示。
can2未启动,启动CAN2接口:
# ifconfig can2 up
ifconfig: SIOCSIFFLAGS: Invalid argument
不能启动,且DEBUG串口中打印如下错误信息。这两条信息应该是linux内核打印出来的错误信息
mcp251x spi1.0: bit-timing not yet defined
mcp251x spi1.0: unable to set initial baudrate!
查看网上信息,原文(出处:How to configure and use CAN bus),如下说明:
bit-timing not yet defined
First run
ip link set can0 type can bitrate 125000 triple-sampling on
then run
ifconfig can0 up
但是使用IP命令后,出现如下信息:
# ip link set can0 type can bitrate 250000
ip: either “dev” is duplicate, or “type” is garbage
查网上信息,这是由于文件系统中的ip命令不支持设置CAN速率,原文(出处:CAN bus Linux driver)如下:
- Set the bitrate before all operations
Example: Set the bitrate of the can0 interface to 125kbps:
# ip link set can0 up type can bitrate 125000
Note: An error occurs when you try to set the bitrate with an old Linux kernel.
- If the following error occurs when you do the last instruction :
ip: either "dev" is duplicate, or "type" is garbage
check that this command:
# which ip
return this message:
/sbin/ip
and not this one :
/bin/ip
If the binary is installed in /bin instead of /sbin, the executable file is a link to busybox and the command to set the bitrate doesn’t work on busybox
- Once the driver is installed and the bitrate is set, the CAN interface has to be started like a standard net interface:
# ifconfig can0 up
- and can be stopped like that:
# ifconfig can0 down
解决方法
花了点时间了解后,猛然醒悟:
- 为了使设置的CAN通讯波特率生效,先用ifconfig can2 down命令关闭CAN接口;
- 然后,操作linux can接口之前,必须先设置CAN通讯波特率,再使用ifconfig can2 up命令启用CAN接口;
板子上的IP命令不支持上述方式设置CAN通讯波特率,而是采用echo命令来设置CAN通讯波特率,如下:
# echo 250000 > /sys/class/net/can2/can_bittiming/bitrate
其中,250000是CAN通讯波特率,表示250Kbps,CAN2表示第3个CAN接口即新增加的CAN接口。