Binary data with pyserial(python serial port)

匿名 (未验证) 提交于 2019-12-03 02:48:02

问题:

serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?

I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem.

回答1:

You need to convert your data to a string

"\xc0\x04\x00" 

Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte "\x00".

One way to do this:

>>> import array >>> array.array('B', [0xc0, 0x04, 0x00]).tostring() '\xc0\x04\x00' 


回答2:

An alternative method, without using the array module:

def a2s(arr):     """ Array of integer byte values --> binary string     """     return ''.join(chr(b) for b in arr) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!