python串口接收数据

1、python使用线程来接收串口数据
2、python3 serial 串口助手的接收读取数据 创建串口助手首先需要创建一个类,重构类的实现过程如下: #coding=gb18030
import threading
import time
import serial
class comthread:
def __init__(self, port=‘com3’):
#构造串口的属性
self.l_serial = none
self.alive = false
self.waitend = none
self.port = port
self.id = none
self.data = none
#定义串口等待的函数
def waiting(self):
if not self.waitend is none:
self.waitend.wait()
def setstopevent(self):
if not self.waitend is none:
self.waitend.set()
self.alive = false
self.stop()
#启动串口的函数
def start(self):
self.l_serial = serial.serial()
self.l_serial.port = self.port
self.l_serial.baudrate = 115200
#设置等待时间,若超出这停止等待
self.l_serial.timeout = 2
self.l_serial.open()
#判断串口是否已经打开
if self.l_serial.isopen():
self.waitend = threading.event()
self.alive = true
self.thread_read = none
self.thread_read = threading.thread(target=self.firstreader)
self.thread_read.setdaemon(1)
self.thread_read.start()
return true
else:
return false
创建好类后,就要实现串口读取的功能,其读取数据的函数如下: 首先要创建一个字符串来存放接收到的数据:
data = ‘’
data = data.encode(‘utf-8’)#由于串口使用的是字节,故而要进行转码,否则串口会不识别
在创建好变量来接收数据后就要开始接收数据: n = self.l_serial.inwaiting()#获取接收到的数据长度
if n:
#读取数据并将数据存入data
data = data + self.l_serial.read(n)
#输出接收到的数据
print(‘get data from serial port:’, data)
#显示data的类型,便于如果出错时检查错误
print(type(data))
将数据接收完后,就要对接收到的数据进行处理,提取出有用信息,由于下位机使用的协议不一样,因此处理的方法也不一样,我使用的协议是**+id+*data+*,因此我的提取方法如下: #获取还没接收到的数据长度
n = self.l_serial.inwaiting()
#判断是否已经将下位机传输过来的数据全部提取完毕,防止之前没有获取全部数据
if len(data)》0 and n==0:
try:
#将数据转换为字符型
temp = data.decode(‘gb18030’)
#输出temp类型,看转码是否成功
print(type(temp))
#输出接收到的数据
print(temp)
将数据按换行分割并输出 car,temp = str(temp).split(“\n”,1)
print(car,temp)
#将temp按‘:’分割,并获取第二个数据
string = str(temp).strip().split(“:”)[1]
#由于前面分割后的数据类型是列表,因此需要转换成字符串,而后按照‘*’分割,得到的也就是我们需要的id和data
str_id,str_data = str(string).split(“*”,1)
print(str_id)
print(str_data)
print(type(str_id),type(str_data))
#判断data最后一位是否是‘*’,若是则退出,若不是则输出异常
if str_data[-1]== ‘*’:
break
else:
print(str_data[-1])
print(‘str_data[-1]!=*’)
except:
print(“读卡错误,请重试!\n”)
其输出结果为:
get data from serial port:b‘id:4a622e29\n\xbf\xa8\xd6\xd0\xbf\xe924\xca\xfd\xbe\xdd\xce\xaa:1*80*\r\n’
《class ‘bytes’》
《class ‘str’》
id:4a622e29
卡中块24数据为:1*80*
id:4a622e29 卡中块24数据为:1*80*
80*
《class ‘str’》 《class ‘str’》
串口助手完整代码如下: #coding=gb18030
import threading
import time
import serial
class comthread:
def __init__(self, port=‘com3’):
self.l_serial = none
self.alive = false
self.waitend = none
self.port = port
self.id = none
self.data = none
def waiting(self):
if not self.waitend is none:
self.waitend.wait()
def setstopevent(self):
if not self.waitend is none:
self.waitend.set()
self.alive = false
self.stop()
def start(self):
self.l_serial = serial.serial()
self.l_serial.port = self.port
self.l_serial.baudrate = 115200
self.l_serial.timeout = 2
self.l_serial.open()
if self.l_serial.isopen():
self.waitend = threading.event()
self.alive = true
self.thread_read = none
self.thread_read = threading.thread(target=self.firstreader)
self.thread_read.setdaemon(1)
self.thread_read.start()
return true
else:
return false
def senddate(self,i_msg,send):
lmsg = ‘’
isok = false
if isinstance(i_msg):
lmsg = i_msg.encode(‘gb18030’)
else:
lmsg = i_msg
try:
# 发送数据到相应的处理组件
self.l_serial.write(send)
except exception as ex:
pass;
return isok
def firstreader(self):
while self.alive:
time.sleep(0.1)
data = ‘’
data = data.encode(‘utf-8’)
n = self.l_serial.inwaiting()
if n:
data = data + self.l_serial.read(n)
print(‘get data from serial port:’, data)
print(type(data))
n = self.l_serial.inwaiting()
if len(data)》0 and n==0:
try:
temp = data.decode(‘gb18030’)
print(type(temp))
print(temp)
car,temp = str(temp).split(“\n”,1)
print(car,temp)
string = str(temp).strip().split(“:”)[1]
str_id,str_data = str(string).split(“*”,1)
print(str_id)
print(str_data)
print(type(str_id),type(str_data))
if str_data[-1]== ‘*’:
break
else:
print(str_data[-1])
print(‘str_data[-1]!=*’)
except:
print(“读卡错误,请重试!\n”)
self.id = str_id
self.data = str_data[0:-1]
self.waitend.set()
self.alive = false
def stop(self):
self.alive = false
self.thread_read.join()
if self.l_serial.isopen():
self.l_serial.close()
#调用串口,测试串口
def main():
rt = comthread()
rt.sendport = ‘**1*80*’
try:
if rt.start():
print(rt.l_serial.name)
rt.waiting()
print(“the data is:%s,the id is:%s”%(rt.data,rt.id))
rt.stop()
else:
pass
except exception as se:
print(str(se))
if rt.alive:
rt.stop()
print(‘’)
print (‘end ok 。’)
temp_id=rt.id
temp_data=rt.data
del rt
return temp_id,temp_data
if __name__ == ‘__main__’:
#设置一个主函数,用来运行窗口,便于若其他地方下需要调用串口是可以直接调用main函数
id,data = main()
print(“******”)
print(id,data)

lora网关采集温室大棚温湿度数据案例
区块链安全体系建设的需求是什么
2017年的智能家电将更加智能?可能还要一段时间
FPGA开发:modelsim仿真流程及波形
具身智能,是机器人的“冷饭热炒”吗?
python串口接收数据
基于CSE7780芯片的智能电能表设计方案
激光设备领域或现大额并购
国际大学生超级计算机竞赛,清华夺ASC、ISC、SC三项超算比赛大满贯
CI24R1/SI24R1 2.4G无线传输技术-无线门铃
FLIR推出“黑黄蜂”个人侦察系统 可提升陆军分队的监视和侦察能力
为什么HTCOneM9被称为史上第三难拆的手机
普及智慧城市,RISC处理器架构是关键
电动牙刷品牌排行榜_国产声波牙刷品牌排行
奥迪这款suv车厉害了,一箱油1200公里,比Q7大,4.7秒破百
浅析ECCV18 DeepMind论文《Look, Listen and Learn》
六种颜色的华为p10、p10plus,就差一种颜色就可以召唤神龙了
网络变压器EMC系列之1:网络变压器扼流圈对EMI电流的阻断作用
VoLTE的优势是什么,你的通话质量提高了没
iPhoneXR仅仅两天破87万预约量 廉价版iPhone更受青睐