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, w开发者_JAVA百科hen 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
.
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'
(i.e. a bytestring, not unicode)
精彩评论