生活随笔
收集整理的這篇文章主要介紹了
python3操作USB设备
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文以讀取USB無線測量設備數據舉例說明。需要用到pyusb模塊和libusb-1.0.dll,詳細說明如下。
一、配置libusb-1.0.dll
下載libusb-1.0.22.7z,根據操作系統來選擇對應的動態庫,如下:
二、安裝USB驅動
打開zadig-2.5.exe選擇菜單:Options->List All Devices,列出當前電腦所有USB設備,鍵盤和鼠標USB設備不用考慮在設備列表中選擇USB設備,點擊“Replace Driver”按鈕安裝USB驅動
三、查詢USB設備的idVendor和idProduct
打開zadig-2.5.exe選擇菜單:Options->List All Devices,列出當前電腦所有USB設備,鍵盤和鼠標USB設備不用考慮USB ID后面的兩個值,分別對應:idVendor和idProduct
四、代碼
def get_usb_devlists():all_devs
= usb
.core
.find
(find_all
=True)dev_list
= []for d
in all_devs
:key
= '{0}{1}'.format(hex(d
.idVendor
), hex(d
.idProduct
))try:dev_u
= usb
.core
.find
(idVendor
=d
.idVendor
, idProduct
=d
.idProduct
)dev_u
.reset
()if dev_u
:dev_u
.set_configuration
() cfg
= dev_u
.get_active_configuration
() intf
= cfg
[(0, 0)]ep
= intf
[0]dev_list
.append
(key
)if key
in CUsb
.dev_dict
: continueCUsb
.dev_dict
[key
] = {'idVendor': d
.idVendor
, 'idProduct': d
.idProduct
, 'thread': False}except Exception
as e
:err_str
= str(e
)print("error!", err_str
)
def __init__(self
, VID
: int=None, PID
: int=None, dev
=None, ep
=None):self
.VID
= VIDself
.PID
= PIDself
.dev_u
= Noneself
.ep
= Noneif VID
and PID
:try:self
.dev_u
= usb
.core
.find
(idVendor
=VID
, idProduct
=PID
)if self
.dev_u
:self
.dev_u
.set_configuration
() cfg
= self
.dev_u
.get_active_configuration
()intf
= cfg
[(0, 0)]self
.ep
= intf
[0]else:print("Can't find device!")except Exception
as e
:print('__init__: ', e
)def read_data(self
):if not self
.ep
:return []key_dict
= {30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9',39: '0', 40: '\n', 55: '.'}result_list
= []data
= []n
= 0inter
= 16while (40 not in data
) or n
< 1: n
+= 1try:if self
.ep
:data
+= self
.ep
.read
(8, 1000) except Exception
as e
:err_str
= str(e
)count
= len(data
)tmp_data
= [data
[i
:i
+ inter
] for i
in range(0, count
, inter
)]result_list
.append
('') for idx
, tmp
in enumerate(tmp_data
):data_str
= self
.get_value_form_8_byte
(tmp
)if data_str
== '\n': result_list
[-1] += data_str
if idx
< len(tmp_data
)-1: result_list
.append
('')continueif (data_str
== '' or data_str
== '0') and result_list
[-1] == '': continueresult_list
[-1] += data_strresult_list
[-1] = ('0' + result_list
[-1]) if (result_list
[-1][0] == '.') else result_list
[-1] return [i
for i
in result_list
if ('\n' in i
) and ('.' in i
)]
總結
以上是生活随笔為你收集整理的python3操作USB设备的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。