pyUSB从sens获取连续的数据流

2024-05-19 00:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个通过usb连接的设备,我正在使用pyUSB连接数据。

这就是我的代码当前的样子:

import usb.core
import usb.util

def main():
    device = usb.core.find(idVendor=0x072F, idProduct=0x2200)

    # use the first/default configuration
    device.set_configuration()

    # first endpoint
    endpoint = device[0][(0,0)][0]

    # read a data packet
    data = None
    while True:
        try:
            data = device.read(endpoint.bEndpointAddress,
                               endpoint.wMaxPacketSize)
            print data

        except usb.core.USBError as e:
            data = None
            if e.args == ('Operation timed out',):

                continue

if __name__ == '__main__':
  main()

它基于鼠标阅读器,但我得到的数据对我来说没有意义:

array('B', [80, 3])
array('B', [80, 2])
array('B', [80, 3])
array('B', [80, 2])

我的猜测是它只读取了实际提供的部分内容?我试过把maxpacketsize设置得更大,但什么都没有。


Tags: 数据coreimportnonereaddataifmain
2条回答

我只是一个偶然的Python用户,所以要小心。如果您的python脚本无法跟上所采样的数据量,那么这就是适合我的。我从一个uC发送到64字节的PC块。我使用缓冲区来保存我的样本,然后将它们保存在文件中或打印出来。我调整数字乘以64(在下面的例子中是10),直到我收到我期望的所有样本。

# Initialization
rxBytes = array.array('B', [0]) * (64 * 10)
rxBuffer = array.array('B')

在一个循环中,我获取新的样本并将其存储在缓冲区中

# Get new samples
hid_dev.read(endpoint.bEndpointAddress, rxBytes)
rxBuffer.extend(rxBytes)

希望这有帮助。

pyUSB以字符串格式发送和接收数据。您收到的数据是ASCII码。需要添加以下行才能正确读取代码中的数据。

data = device.read(endpoint.bEndpointAddress,
                           endpoint.wMaxPacketSize)

RxData = ''.join([chr(x) for x in data])
print RxData

函数chr(x)将ASCII代码转换为字符串。这应该能解决你的问题。

相关问题 更多 >

    热门问题