将字符串发送到 serial.to_bytes 无效

Sending string to serial.to_bytes not working

我正在尝试发送一个包含命令的字符串变量。

像这样:

value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))

上面那个失败了。不会报错。

但是当我发送这样的值时它起作用了:

self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))

我也试过像这样发送字符串:

self.s.write(serial.to_bytes(str(value)))

还是不行。有人可以告诉我如何通过存储在字符串中来发送值吗?

我想做这件事:

value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"

并发送值。

谢谢!

serial.to_bytes 将序列作为输入。您应该删除 value 周围的双引号以传递整数序列而不是 str 表示您要传递的序列:

value = [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
self.s.write(serial.to_bytes(value))  # works now

在第一种情况下,您发送了一个表示 "[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]" 的字节序列。现在,您将按预期发送序列 [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]


如果要发送字符串,只需将其发送为 bytes:

# Python 2
self.s.write('this is my string')
text = 'a string'
self.s.write(text)

# Python 3
self.s.write(b'this is my string')
text = 'a string'
self.s.write(text.encode())

对于序列:

for value in values:
    # Python 2
    self.s.write(value)

    # Python 3
    self.s.write(value.encode())

如果传递整数列表对您有用,那么只需将您的十六进制表示形式转换为整数并将它们放入列表中即可。

详细步骤:

  1. 打开一个python解释器

  2. 导入serial并打开串口,命名为ser.

  3. 复制下面的代码并将其粘贴到python解释器中:

代码:

command = '310a320a330a'
hex_values = ['0x' + command[0:2],  '0x' + command[2:4],
              '0x' + command[4:6],  '0x' + command[6:8],
              '0x' + command[8:10], '0x' + command[10:12]]
int_values = [int(h, base=16) for h in hex_values]
ser.write(serial.to_bytes(int_values))

它的效果和这个是一样的:

ser.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))

实际上你可以测试 int_values == [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]True 所以你写的是完全一样的东西。