当前位置: 首页 > news >正文

Ubuntu18.04 python 开发usb通信

一、安装环境

1.安装pip

sudo python3 get-pip.py 

sudo -i
apt update
apt install python3-pip

确定pip是否安装成功:

xxx-desktop:~$ pip3 --versionpip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)

2.安装pyusb

pip3 install pyusb --user

3.安装libusb

pip3 install libusb --user

二、测试

1.在HOME目录新建一个test.py文件

$ cd ~
$ touch test.py

2.编辑文件

$ vim test.py 
# -*- coding: utf-8 -*-import usb.coredev = usb.core.find(find_all=True)      #find all usb devices
for i in dev:print(i)        #print information of all usb devices

3.执行

$ python3 Usb.py 
DEVICE ID 0bda:0411 on Bus 002 Address 002 =================bLength                :   0x12 (18 bytes)bDescriptorType        :    0x1 DevicebcdUSB                 :  0x320 USB 3.2bDeviceClass           :    0x9 HubbDeviceSubClass        :    0x0bDeviceProtocol        :    0x3bMaxPacketSize0        :    0x9 (9 bytes)idVendor               : 0x0bdaidProduct              : 0x0411bcdDevice              :  0x101 Device 1.01iManufacturer          :    0x1 Error Accessing StringiProduct               :    0x2 Error Accessing StringiSerialNumber          :    0x0 bNumConfigurations     :    0x1CONFIGURATION 1: 0 mA ====================================bLength              :    0x9 (9 bytes)bDescriptorType      :    0x2 ConfigurationwTotalLength         :   0x1f (31 bytes)bNumInterfaces       :    0x1bConfigurationValue  :    0x1iConfiguration       :    0x0 bmAttributes         :   0xe0 Self Powered, Remote WakeupbMaxPower            :    0x0 (0 mA)INTERFACE 0: Hub =======================================bLength            :    0x9 (9 bytes)bDescriptorType    :    0x4 InterfacebInterfaceNumber   :    0x0bAlternateSetting  :    0x0bNumEndpoints      :    0x1bInterfaceClass    :    0x9 HubbInterfaceSubClass :    0x0bInterfaceProtocol :    0x0iInterface         :    0x0 ENDPOINT 0x81: Interrupt IN ==========================bLength          :    0x7 (7 bytes)bDescriptorType  :    0x5 EndpointbEndpointAddress :   0x81 INbmAttributes     :   0x13 InterruptwMaxPacketSize   :    0x2 (2 bytes)bInterval        :    0x8......

三、数据通信例程

驱动代码:usb_dev.py

import usb.core
import usb.utilEP_IN = 0x81
EP_OUT = 0x01dev_handle = None
kernelDriverDetached = 0#
#  usb_dev_open.
#
def usb_dev_open(vendor_id, product_id):global dev_handleglobal kernelDriverDetacheddev_handle = NonekernelDriverDetached = 0	if dev_handle is not None:usb.util.release_interface(dev_handle, 0)if kernelDriverDetached:dev_handle.attach_kernel_driver(0)usb.util.dispose_resources(dev_handle)dev_handle = Nonedev_handle = usb.core.find(idVendor=vendor_id, idProduct=product_id)if dev_handle is None:return Falsedev_handle.set_configuration()try:if dev_handle.is_kernel_driver_active(0):dev_handle.detach_kernel_driver(0)kernelDriverDetached = 1except NotImplementedError:passtry:usb.util.claim_interface(dev_handle, 0)return Trueexcept usb.core.USBError:return False#
#  usb_dev_close.
#
def usb_dev_close():global dev_handleglobal kernelDriverDetachedif dev_handle is not None:usb.util.release_interface(dev_handle, 0)usb.util.dispose_resources(dev_handle)dev_handle = NonekernelDriverDetached = 0#
#  usb_dev_write_sync.
#
def usb_dev_write_sync(Datas, DataLen, timeout):global dev_handleif dev_handle is None:return Falseret = dev_handle.write(EP_OUT, Datas)if ret > 0:return Trueprint("usb_dev_write_sync error,", ret)return False    #
#  usb_dev_read_sync.#
def usb_dev_read_sync(Buf, bufsz, timeout):global dev_handleif dev_handle is None:return Falsedata = dev_handle.read(EP_IN, bufsz, timeout=timeout)Buf[:] = datareturn Buf    	

 主文件:main.py

import usb_devif __name__ == "__main__":# Open USB device with VID=0x1234 and PID=0x1001if usb_dev.usb_dev_open(0x1234, 0x1001) == False:print("usb_dev_open fail!")exit(-1)print("usb_dev_open ok")TxBuff = bytearray(512)            #端点最大数据为512字节RxBuff = bytearray(512)usb_dev.usb_dev_write_sync(TxBuff, 512, 1000)            #超时1000msusb_dev.usb_dev_read_sync(RxBuff, 512, 1000)             #超时1000msprint("RxBuff:",RxBuff)usb_dev.usb_dev_close()      

四、实际应用

在我的实际应用中下位机是一个高速USB图像模组,接收到上位机发送的获取图像指令后,将640x480像素的灰度图分包(每包最大512byte)发送给上位机。之前是在linux系统下使用libusb能正常运行,后面由于需要使用python开发算法,为了方便python程序直接获取图像,就尝试在python程序中直接调用USB函数进行发送和接收,不过存在不能完全接收下位发送的分包数据,每次只能接收前两个包,可能是由于python执行效率太低的原因。

http://www.lryc.cn/news/39036.html

相关文章:

  • RabbitMq 消息确认机制详解 SpringCloud
  • 后台导航布局
  • 设计模式——抽象工厂模式(创建型)
  • Java面试题--SpringMVC的执行流程
  • c# 32位程序突破2G内存限制
  • 【C语言】指针详解总结
  • Java加解密(八)工具篇
  • Go框架三件套(Web/RPC/ORM)
  • HR问:假如公司给不到你期望的薪资怎么办?这个问题该如何体面地回答?
  • LearnOpenGL-高级OpenGL-2.模板测试
  • 【Git从入门到精通】Git入门
  • 软件测试18
  • C语言实现快速排序(hoare法、挖坑法、前后指针法与非递归实现)——不看后悔系列
  • 如何为系统可靠性的量化提供依据
  • 量化投资中的因子是什么?因子是如何分类的,包括哪些?
  • 力扣-修复表中的名字
  • 【博客633】linux vxlan设备工作原理
  • 3.12学习周报
  • 电力电子中逐波限流控制以及dsp实现
  • 【数据结构】 顺序表
  • Elasticsearch 集群规划- 单台机器核心数计算公式
  • Tesla都使用什么编程语言?
  • 1143. 最长公共子序列——【Leetcode每日刷题】
  • 【并发基础】线程的通知与等待:obj.wait()、obj.notify()、obj.notifyAll()详解
  • css黏性定位-实现商城的分类滚动的标题吸附
  • @Component和@bean注解在容器中创建实例区别
  • 不写注释就是垃圾
  • 深信服一面
  • 【C语言】深度理解指针(中)
  • 步进电机运动八大算法