python串口连续数据_Python代码从串口连续接收可变数据

本文介绍了如何使用Python进行串口通信,通过示例代码展示了如何连续从串口接收并校验数据。代码适用于Python 3,包括了在主线程和线程中读取串口数据的方法,以及数据的开始、结束标志和校验过程。
摘要由CSDN通过智能技术生成

通常,您与微通信所做的工作是将单个字符用于轻量级或创建通信协议。基本上你有一个开始标志,结束标志和某种校验和,以确保数据正确传输。有很多方法可以做到这一点。

以下代码适用于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值