我定义了一堆单独的十六进制字符,我需要将它们写入设备串行端口。我如何从它们创建一个字节数组? 例如:
import serial
# There is a series of predefined hex characters for talking to this device. Some
# These are just some random examples I made up
START_BYTE = 0x03
END_BYTE = 0x10
RANDOM_BYTE1 = 0xCE
RANDOM_BYTE2 = 0xAB
# Assume I opened port and is connected
sp = serial.open()
# Now in some random method I want to write to the port the sequence of
# [START_BYTE, RANDOM_BYTE1, END_BYTE]
# How would I write this? I tried
sp.write([START_BYTE, RANDOM_BYTE1, END_BYTE])
sp.write(bytearray([START_BYTE, RANDOM_BYTE1, END_BYTE]))
# But I do not get the response on the machine I want.
最终RANDOM_BYTE将是一些数据位,可能是1到10个字节,具体取决于具体情况。所以它会是
[START_BYTE, DATA_BYTES, END_BYTE]
我做错了什么?
我正在使用python 2.7
答案 0 :(得分:2)
您需要的是bytes
(或str
以下......< 2.6?)。
>>> bytes(bytearray([0x03, 0xce, 0xab]))
'\x03\xce\xab'