实在不想那种中规中矩的写东西了,写的自己都看不下去了,想到啥就写啥吧!
聊两句
最近没事就看了一CAN总线相关的东西,平时工作上接触的不多,大部分时间都是在移动端的自动化上,服务端的自动化上面,针对这块了解的非常非常的少。不看就会焦虑。
因为平时工作用的不多,也就是看一下混个眼熟吧,记录下来一些自己觉得重要的信息,以便后面使用。
安装
一行命令吧
pip install python-can
没有CAN硬件咋办
我也是看到知乎上的一个帖子才知道Kvaser这个软件。链接地址
上个示例代码吧,看看是什么样子
- 代码①
# coding:utf-8
"""
This example shows how sending a single message works
"""
import can
def send_one():
""" Sends a single message."""
# Using specific buses works similar:
# bus = can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)
# bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=250000)
# bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
bus = can.interface.Bus(bustype='kvaser', channel=0, bitrate=250000)
msg = can.Message(arbitration_id=0xc0ffee, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False)
try:
bus.send(msg)
print("Message sent on {}".format(bus.channel_info))
except can.CanError:
print("Message NOT sent")
if __name__ == '__main__':
send_one()
- 代码②
# coding:utf-8
"""
通过代码设置实现
"""
import can
can.rc['interface'] = 'kvaser'
can.rc['channel'] = '0'
can.rc['bitrate'] = 250000
from can.interface import Bus
bus = Bus()
# 或者可以通过以下方式
# bus = Bus(bustype='kvaser', channel=0, bitrate=250000)
msg = can.Message(arbitration_id=0xc0ffee, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=False)
try:
bus.send(msg)
print("Message sent on {}".format(bus.channel_info))
except can.CanError:
print("Message NOT sent")
上面两种示例代码主要是体现了两种bus的创建方式,针对CAN的配置还有更多的方式,比如配置文件,环境变量,还有刚才的代码中配置。下面看看有哪些配置方式。
配置方式
配置文件
在linux系统中,配置文件主要在以下路径中搜索:
- ~/can.conf
- /etc/can.conf
- $HOME/.can
- $HOME/.canrc
在Windows系统中的配置文件路径:
- %USERPROFILE%/can.conf
- can.ini (当前工作目录)
- %APPDATA%/can.ini
can.ini文件长啥样呢?
[default]
interface = kvaser
channel = 0
bitrate = 250000
除了设置default项,还可以设置别的项,比如可以配置更多的CAN硬件信息,配置文件样式如下:(没有的配置项可以共享default的配置)
[default]
interface = <the name of the interface to use>
channel = <the channel to use by default>
bitrate = <the bitrate in bits/s to use by default>
[HS]
*# All the values from the 'default' section are inherited*
channel = <the channel to use>
bitrate = <the bitrate in bits/s to use. i.e. 500000>
[MS]
*# All the values from the 'default' section are inherited*
channel = <the channel to use>
bitrate = <the bitrate in bits/s to use. i.e. 125000>
那怎么使用呢,在创建BUS对象的时候传入context参数就可以了
from can.interface import Bus
hs_bus = Bus(context='HS')
ms_bus = Bus(context='MS')
有了配置文件,就在创建BUS对象的时候不需要传递参数了
# coding: utf-8
"""
通过with语句执行can
"""
from can import CanError