简体   繁体   中英

Communication with usb device using pyusb

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?

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'

(ie a bytestring, not unicode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM