一、概述

1.介绍

python-can库为Python提供了控制器局域网的支持,为不同的硬件设备提供了通用的抽象,并提供了一套实用程序,用于在CAN总线上发送和接收消息。

支持硬件接口:

Name

Documentation

"socketcan"

SocketCAN

"kvaser"

Kvaser’s CANLIB

"serial"

CAN over Serial

"slcan"

CAN over Serial / SLCAN

"ixxat"

IXXAT Virtual CAN Interface

"pcan"

PCAN Basic API

"usb2can"

USB2CAN Interface

"nican"

NI-CAN

"iscan"

isCAN

"neovi"

neoVI

"vector"

Vector

"virtual"

Virtual

"canalystii"

CANalyst-II

"systec"

SYSTEC interface

2.环境搭建

Python安装:https://www.python.org/ftp/python/3.7.9/python-3.7.9-amd64.exe

PCAN-USB驱动:https://www.peak-system.com/fileadmin/media/files/pcan-basic.zip

库:pip install python-can

3.参考文档

https://python-can.readthedocs.io/en/master/#

二、常用方法

1.接收报文

from can.interfaces.pcan.pcan import PcanBusdef bus_recv():"""轮询接收消息"""try:while True:msg = bus.recv(timeout=100)print(msg)except KeyboardInterrupt:passif __name__ == '__main__':bus = PcanBus(channel='PCAN_USBBUS1', bitrate=500000)bus_recv()

2.发送报文

from can.interfaces.pcan.pcan import PcanBusdef bus_send():"""can消息发送"""while True:time.sleep(0.02)try:bus.send(msg)print("消息发送 {}".format(bus.channel_info))except can.CanError:print("消息未发送")if __name__ == '__main__':msg = can.Message(arbitration_id=0x181DFF00, data=[0xEE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFF, 0xFF, 0xFE],is_extended_id=True)  # 报文bus = PcanBus(channel='PCAN_USBBUS1', bitrate=500000)bus_send()

3.定期发送报文

def bus_send_periodic():"""周期发送报文"""print("开始每200毫秒发送一条消息。持续时间10s")task = bus.send_periodic(msg, 1.5)  # 定期发送if not isinstance(task, can.ModifiableCyclicTaskABC):  # 断言task类型print("此接口似乎不支持")task.stop()returntime.sleep(5)  # 持续时间print("发送完成")print("更改运行任务的数据以99开头")msg.data[0] = 0x99task.modify_data(msg)  # 修改data首字节time.sleep(10)task.stop()print("停止循环发送")print("将停止任务的数据更改为单个 ff 字节")msg.data = bytearray([0xff])  # 重新定向datamsg.dlc = 1  # 定义data长度task.modify_data(msg)  # 修改datatime.sleep(10)print("重新开始")task.start()  # 重新启动已停止的周期性任务time.sleep(10)task.stop()print("完毕")if __name__ == '__main__':msg = can.Message(arbitration_id=0x181DFF00, data=[0xEE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFF, 0xFF, 0xFE],is_extended_id=True)  # 报文bus = PcanBus(channel='PCAN_USBBUS1', bitrate=500000)bus_send_periodic()

4.循环收发消息

from can.interfaces.pcan.pcan import PcanBusdef send_cyclic(stop_event):"""循环发送消息"""print("开始每1秒发送1条消息")start_time = time.time()while not stop_event.is_set():msg.timestamp = time.time() - start_timebus.send(msg)print(f"tx: {msg}")time.sleep(1)print("停止发送消息")def receive(stop_event):"""循环接收消息"""print("开始接收消息")while not stop_event.is_set():rx_msg = bus.recv(1)if rx_msg is not None:print(f"rx: {rx_msg}")print("停止接收消息")def send_and_recv_msg():"""发送一个消息并接收一个消息,需要双通道CAN"""stop_event = threading.Event()t_send_cyclic = threading.Thread(target=send_cyclic, args=(stop_event,))t_receive = threading.Thread(target=receive, args=(stop_event,))t_receive.start()t_send_cyclic.start()try:while True:time.sleep(0)  # yieldexcept KeyboardInterrupt:pass  # 正常退出stop_event.set()time.sleep(0.5)if __name__ == '__main__':msg = can.Message(arbitration_id=0x181DFF00, data=[0xEE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFF, 0xFF, 0xFE],is_extended_id=True)  # 报文bus = PcanBus(channel='PCAN_USBBUS1', bitrate=500000)send_and_recv_msg()

python-can库基于PCAN-USB使用方法相关推荐

  1. dos系统不能安装python模块,无法使用pip命令安装python第三方库的原因及解决方法...

    再dos中无法使用pip,命令主要是没有发现这个命令.我们先找到这个命令的位置,一般是在python里面的scripts文件夹里面.我们可以把dos切换到对应的文件夹,再使用pip命令就可以了. 如果 ...

  2. python安装第三方库-python第三方库的四种安装方法

    讲解一下python第三方库的四种安装方法 问题场景 (我的操作系统windows): 我使用pip install selenium 发现先爆出一大段黄色警告日志,最后是两段红色的错误日志,无法成功 ...

  3. python第三方库安装有哪些要求,python第三方库的四种安装方法

    讲解一下python第三方库的四种安装方法 问题场景 (我的操作系统windows): 我使用pip install selenium 发现先爆出一大段黄色警告日志,最后是两段红色的错误日志,无法成功 ...

  4. python snmp_cmds库snmpwalk 中文正常显示方法

    修改python snmp_cmds库commands.py文件中调用snmpwalk命令中的参数选项,是命令输出带数据类型 'snmpwalk', '-OQfn', '-Pe', '-t', str ...

  5. Python Requests库使用2:请求方法

    GitHub API URL: https://developer.github.com HTTP verbs1 Where possible, API v3 strives to use appro ...

  6. Python numpy库 shape属性和reshape()方法

    shape是数组array的属性:reshape()是数组array的方法 shape属性可以获得当前array的形状: import numpy as npa = np.array([1, 2, 3 ...

  7. python的gui库哪个好_常用的13 个Python开发者必备的Python GUI库

    [Python](http://www.blog2019.net/tag/Python?tagId=4)是一种高级编程语言,它用于通用编程,由Guido van Rossum 在1991年首次发布.P ...

  8. [转载] python常用库

    参考链接: Python–新一代语言 转载至:https://www.cnblogs.com/jiangchunsheng/p/9275881.html 今天我将介绍20个属于我常用工具的Python ...

  9. Python开发者必知的 11 个 Python GUI 库,你用过几个?

    Python是一种高级编程语言,它用于通用编程,由Guido van Rossum 在1991年首次发布.Python 的设计着重于代码的可读性. Python有一个非常大的标准库,并且有一个动态类型 ...

  10. Python机器学习库scikit-learn实践

    Python机器学习库scikit-learn实践 zouxy09@qq.com http://blog.csdn.net/zouxy09 一.概述 机器学习算法在近几年大数据点燃的热火熏陶下已经变得 ...

最新文章

  1. python播放本地视频教程_怎样用python播放视频
  2. 无法转化为项目财富的技术或功能就是垃圾
  3. java ee是什么_死磕 java集合之HashSet源码分析
  4. php mysql 查询数据出现连接重置_php使用mysql和mysqli连接查询数据
  5. 每日三道前端面试题--vue 第一弹
  6. [2019杭电多校第六场][hdu6641]TDL
  7. react 点击使父元素消失_在 React 组件中使用 Refs 指南
  8. 如何设置PDFjs 页面标题
  9. 三角网导线平差实例_三角网闭合导线平差计算表0
  10. 软件项目管理相关(生存期模型、FP、PERT)
  11. Bresenham画圆 正负画圆法 中点画圆法
  12. 【coppeliasim】高效传送带
  13. dbm和发射功率得对照表
  14. 802.11成帧封装实现(三)
  15. 在中国大陆,XGP对比Steam有什么优势?
  16. [nova]nova api执行过程分析
  17. Beta冲刺-第四天
  18. JavaScript的压缩工具
  19. 一文读懂卫星导航测量天线
  20. 树莓派raspberry搭建打印cups服务器连接EPSON_L360打印机供ios安卓使用

热门文章

  1. 如何写一份风投喜欢的商业计划书?【转载】
  2. plupload插件上传总结(分片上传,php后端处理)
  3. 无版权高清图片素材库pixabay
  4. 基于YOLO的新型RGB-D融合方法对行人进行检测和3D定位
  5. [APIO2014]序列分割
  6. EPLAN学习笔记——常用操作步骤
  7. 聊聊激光雷达原理之i-TOF
  8. Mac | 关于MacBook教育优惠注意事项
  9. 电机与拖动 - 1 绪论
  10. 数字媒体概论——系统篇