pyUSB get a continuous stream of data from sensor

14,129

Solution 1

pyUSB sends and receives data in string format. The data which you are receiving is ASCII codes. You need to add the following line to read the data properly in the code.

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

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

The function chr(x) converts ASCII codes to string. This should resolve your problem.

Solution 2

I'm only an occasional Python user so beware. If your python script cannot keep up with the amount of data being sampled, then this is what works for me. I'm sending from a uC to the PC blocks of 64 bytes. I use a buffer to hold my samples and later I save them in a file or plot them. I adjust the number multiplying 64 (10 in the example below) until I receive all the samples I was expecting.

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

Within a loop, I get the new samples and store them in the buffer

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

Hope this helps.

Share:
14,129
Stupid.Fat.Cat
Author by

Stupid.Fat.Cat

I like to sleep, a lot....

Updated on July 06, 2022

Comments

  • Stupid.Fat.Cat
    Stupid.Fat.Cat almost 2 years

    I have a device that's connected through usb and I'm using pyUSB to interface with the data.

    This is what my code currently looks like:

    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()
    

    It is based off the mouse reader, but the data that I'm getting isn't making sense to me:

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

    My guess is that it's reading only a portion of what's actually being provided? I've tried settign the maxpacketsize to be bigger, but nothing.