Ubuntu中使用pyUSB讀取鼠標或鍵盤的數據程序


參考 :http://www.orangecoat.com/how-to/read-and-decode-data-from-your-mouse-using-this-pyusb-hack

要注意的問題:

在ubuntu中USB的使用需要root權限。所以普通情況下即使程序沒錯也會導致USBError。解決的辦法:在終端下以root方式打開python的IDE。Eclipse的pydev不能在root下打開,除非在root情況也裝個pydev。最好是用spyder,雖然編輯起來沒有eclipse方便,但是也很不錯了。

如果程序運行錯誤而退出,會usb設備無反應,重新插拔usb即可。

import usb
dev = usb.core.find(idVendor= 0x24ae, idProduct = 0x2000)
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
interface = 0
endpoint = dev[0][(0,0)][0]
if dev.is_kernel_driver_active(interface) is True:
    dev.detach_kernel_driver(interface)
    usb.util.claim_interface(dev, interface)
collected = 0
attempts = 50
while collected <attempts:
    try:
        data = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
        collected += 1
        print data
    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            continue
usb.util.release_interface(dev, interface)
dev.attach_kernel_driver(interface)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM