通常,您与微通信所做的工作是将单个字符用于轻量级或创建通信协议。基本上你有一个开始标志,结束标志和某种校验和,以确保数据正确传输。有很多方法可以做到这一点。
以下代码适用于Python 3.您可能必须对字节数据进行更改。
# On micro
data = b"[Hello,1234]"
serial.write(data)
在电脑上,你会运行,如果您使用的是GUI
def read_data(ser, buf=b'', callback=None):
if callback is None:
callback = print
# Read enough data for a message
buf += ser.read(ser.inwaiting()) # If you are using threading +10 or something so the thread has to wait for more data, this makes the thread sleep and allows the main thread to run.
while b"[" not in buf or b"]" not in buf:
buf += ser.read(ser.inwaiting())
# There may be multiple messages received
while b"[" in buf and b']' in buf:
# Find the message
start = buf.find(b'[')
buf