Ubuntu18.04 python 开发usb通信
创始人
2024-06-02 04:47:17
0

一、安装环境

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执行效率太低的原因。

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...