前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 串口两进程同时读写

Python3 串口两进程同时读写

作者头像
py3study
发布2020-01-13 11:19:58
1.4K0
发布2020-01-13 11:19:58
举报
文章被收录于专栏:python3
代码语言:javascript
复制
通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出
代码语言:javascript
复制
import threading,time
import serial
import string


class SerThread:
    def __init__(self, Port=0):
        #初始化串口、blog文件名称
        self.my_serial = serial.Serial()
        self.my_serial.port=Port
        self.my_serial.baudrate = 9600
        self.my_serial.timeout = 1        
        self.alive = False
        self.waitEnd = None
        fname=time.strftime("%Y%m%d")#blog名称为当前时间
        self.rfname='r'+fname #接收blog名称
        self.sfname='s'+fname #发送blog名称
        self.thread_read= None
        self.thread_send=None      
             

    def waiting(self):
        # 等待event停止标志
        if not self.waitEnd is None:
            self.waitEnd.wait()

    def start(self):
        #开串口以及blog文件 
        self.rfile=open(self.rfname,'w')
        self.sfile=open(self.sfname,'w')
        self.my_serial.open()
             
        if self.my_serial.isOpen():
            self.waitEnd = threading.Event()
            self.alive = True
            
            self.thread_read = threading.Thread(target=self.Reader)
            self.thread_read.setDaemon(True)
            
            self.thread_send=threading.Thread(target=self.Sender)
            self.thread_send.setDaemon(True)
            
            self.thread_read.start()
            self.thread_send.start()
            return True
        else:
            return False

   
    def Reader(self):
        while self.alive:
            try:
                n=self.my_serial.inWaiting()
                data=''
                if n:
                    data= self.my_serial.read(n).decode('utf-8')             
                    print ('recv'+' '+time.strftime("%Y-%m-%d %X")+' '+data.strip())
                    print (time.strftime("%Y-%m-%d %X:")+data.strip(),file=self.rfile)
                    if len(data)==1 and ord(data[len(data)-1])==113: #收到字母q,程序退出
                        break
            except Exception as ex:
                print (ex)
               

        self.waitEnd.set()
        self.alive = False
    
    def Sender(self):
        while self.alive:
            try:
                snddata=input("input data:\n")
                self.my_serial.write(snddata.encode('utf-8'))
                print ('sent'+' '+ time.strftime("%Y-%m-%d %X"))
                print (snddata,file=self.sfile)  
                
            except Exception as ex:
                print (ex)
        
        self.waitEnd.set()
        self.alive = False                   
                
        

    def stop(self):
        self.alive = False
        #self.thread_read.join()
        #self.thread_send.join()
        if self.my_serial.isOpen():
            self.my_serial.close()
        self.rfile.close()
        self.sfile.close()
            

if __name__ == '__main__':    
    
    ser = SerThread('com4')
    try:
        if ser.start():
            ser.waiting()
            ser.stop()
        else:
            pass;            
    except Exception as ex:
        print (ex)

    if ser.alive:
        ser.stop()

    print ('End OK .');
    del ser; 
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/07/23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档