python读写USB端口

系统:WIN10 64位

python版本:3.6.5

USB设备:STM32F411

STM32F411模拟了一个简单的HID设备,有一个IN端口和一个OUT端口,当OUT端口收到数据后,再把收到的数据写回到IN端口,这样就可以做一个环回测试

代码:

import usb.core
import usb.util
import sys
import threading
import time

VID=0x0483
PID=0x5750
 
dev =  usb.core.find(idVendor=VID, idProduct=PID)
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]

print(intf)

write_ep = usb.util.find_descriptor(
    intf,
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_OUT
)

read_ep = usb.util.find_descriptor(
    intf,
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_IN
    )

def write_endpoint_thread():
    while True:
        try:
            write_ep.write("0123456789")
        except:
            print("write error")
    

def read_endpoint_thread():
    while True:
        try:
            data = read_ep.read(64)
            size = len(data)
            if size > 0:
                print("recv %d bytes:"%size,end='')
                for i in range(0,size):
                    print ("%c"%data[i],end='')
                print ('')
        except:
            print("no data")

    

def main():
    r = threading.Thread(target=read_endpoint_thread)
    w = threading.Thread(target=write_endpoint_thread)
    r.start()
    w.start()
    r.join()
    w.join()
    dev.reset()

if __name__ == '__main__':
    main()
    

输出结果:

python读写USB端口_第1张图片

你可能感兴趣的:(Python,USB)