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

时间:2021-01-14 18:12:05

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')不工作

1 个解决方案

#1


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 ? or like a diamond with a question mark

问题是你不能只是打印随机字节(“\ x ##”)到终端,并希望看到有意义的东西......终端显示无法解码的字符?或者像带有问号的钻石

>>> '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

虽然出于任何奇怪的原因我的终端没有添加任何东西?到那个特定的字符串

#1


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 ? or like a diamond with a question mark

问题是你不能只是打印随机字节(“\ x ##”)到终端,并希望看到有意义的东西......终端显示无法解码的字符?或者像带有问号的钻石

>>> '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

虽然出于任何奇怪的原因我的终端没有添加任何东西?到那个特定的字符串