Communication with usb device using pyusb

user800021 picture user800021 · Jun 15, 2011 · Viewed 7.7k times · Source

I am using a module called pyUSB version 1.6 and am trying to communicate with a sensor.

I have set up the connection and can read from the ROM on the sensor. The sensor, when connected, has a master/slave relationship so I need to send a message to the sensor to receive the data I need.

Now, the write function can only accept a string or read-only buffer. I need to send the USB device the hexadecimal bytes 0xFE, 0x04, 0x00, 0x03, 0x00, 0x01, 0xD5, 0xC5.
I'm unsure how to encode that as a string or read-only buffer.

Here is how one calls the write method. This is the sample code they provide.

# write bytes (serial mode)

print h.write('Hello world!\r\n")

How would I transfer the hexadecimal bytes?

Answer

Thomas K picture Thomas K · Jun 15, 2011
byte_ints = [0xFE, 0x04, 0x00, 0x03, 0x00, 0x01, 0xD5, 0xC5] # Python recognises these as hex.
byte_str = "".join(chr(n) for n in byte_ints)

Alternatively, you can just put \x before each pair of hex digits in a string:

'\xfe\x04\x00\x03\x00\x01\xd5\xc5'

In Python 3, that needs to be:

b'\xfe\x04\x00\x03\x00\x01\xd5\xc5'

(i.e. a bytestring, not unicode)