发送字符串到serial.to_bytes不起作用

时间:2016-09-10 09:54:04

标签: python pyserial

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

像这样:

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]"

并发送值。

谢谢!

2 个答案:

答案 0 :(得分:4)

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 :(得分:2)

如果传递整数列表对你有用,那么只需将十六进制表示转换为整数并将它们放在列表中。

详细步骤:

  1. 打开python解释器

  2. 导入serial并打开一个串口,将其称为ser

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

  4. 代码:

    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,所以你写的是完全相同的东西。

相关问题