问题描述
我正在尝试发送一个包含命令的字符串变量.
I am trying to send a string variable contains the command.
像这样:
value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
上面的失败了.不会出错.
The above one fails. Won't give any error.
但是当我发送这样的值时它正在工作:
But it's working when I send a value like this:
self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
我也尝试过发送这样的字符串:
I also tried sending string like this:
self.s.write(serial.to_bytes(str(value)))
还是不行.有人可以告诉我如何通过存储在字符串中来发送值吗?
Still not working. Can someone please let me know how to send the value by storing in string?
我想做这件事:
value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"
并发送值.
谢谢!
推荐答案
如果传递整数列表对您有用,那么只需将您的十六进制表示转换为整数并将它们放入列表中.
If passing a list of integers works for you then just convert your hexadecimal representations into integers and put them in a list.
详细步骤:
打开一个python解释器
Open a python interpreter
导入serial
并打开一个串口,命名为ser
.
Import serial
and open a serial port, call it ser
.
复制下面的代码并粘贴到python解释器中:
Copy the code below and paste it in the python interpreter:
代码:
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))
它会产生与仅此相同的效果:
It will have the same effect that just this:
ser.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
实际上你可以测试 int_values == [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
是 True
所以你写的完全一样.
actually you can test that int_values == [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
is True
so you are writing exactly the same thing.
这篇关于将字符串发送到 serial.to_bytes 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!