简体   繁体   English

python发送十六进制字符串到串行端口

[英]python sending a hex string to serial port

I am trying to send a hexadecimal string to a serial port and it has to be in the following format '\\x02\\x81....' this is my code 我正在尝试将十六进制字符串发送到串行端口,并且必须采用以下格式“ \\ x02 \\ x81 ....”,这是我的代码

from binascii import unhexlify
string='0281E1B1'
print unhexlify(string)

gives me some randon symbols ?a+ instead of \\x02\\x81\\xE1\\xB1 I have python 2.7 so decode('hex') isnt working either 给我一些randon符号?a +而不是\\ x02 \\ x81 \\ xE1 \\ xB1我有python 2.7,所以解码('hex')都不起作用

you are doing it right .... you just need to send it over the port 您做对了....您只需要通过端口发送它

print repr(unhexlify(my_string))

my_serial.write(unhexlify(my_string))

#or 

my_serial.write(my_string.decode("hex"))

the problem is you cant just print random bytes( "\\x##" ) to the terminal and expect to see something that makes sense ...the terminal displays characters it cannot decode a ? 问题是您不能只向终端打印随机字节( "\\x##" )并期望看到有意义的内容...终端显示无法解码的字符? or like a diamond with a question mark 或像带有问号的钻石

>>> '0281E1B1'.decode("hex")
'\x02\x81\xe1\xb1'
>>> print '0281E1B1'.decode("hex")
☻üß▒
>>> '0281E1B1'.decode("hex") == unhexlify('0281E1B1')
True

although for whatever weird reason my terminal didnt add any ? 尽管出于某种奇怪的原因,我的终端没有添加任何内容? to that particular string 到那个特定的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM