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

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

并发送值。

谢谢!

最佳答案

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())

关于python - 将字符串发送到 serial.to_bytes 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39424865/

相关文章:

python - Revit Python 拾取对象/选择对象

python - 使用pyserial发送二进制数据

python - Raspberry Pi 2/Python + 多传感器输出?

python - 收到 pyserial 错误 "TypeError: ' >' not supported between instances of ' 字节' 和 'int'

python - 使用带有 Python/Pyserial 的 C/C++ DLL 与 Opticon 条码阅读器通信

python - 如何使用 C 或 Python 将 CR/LF 行结尾写入串口?

python - 如何使用python获取zip文件中所有文件(或给定文件名)的偏移值?

python - 如何将值与反斜杠进行比较?

python - 将单个字符与它们之间的单个空格组合在一起

python - 有没有更快的方法在 python 中创建 (0,1) 组合列表?