Python3 实现串口两进程同时读写

yipeiwu_com6年前Python基础

通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出

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; 

以上这篇Python3 实现串口两进程同时读写就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python操作json的方法实例分析

Python操作json的方法实例分析

本文实例讲述了Python操作json的方法。分享给大家供大家参考,具体如下: python中对json操作方法有两种,解码loads()和编码dumps() 简单来说: impor...

详解python中的数据类型和控制流

上一篇文章中我们介绍了 python 语言的几个特点,并在最后留了一个问题,python 除了上下执行以外有没有其他的执行方式。 今天我们就来介绍 python 中的数据类型和控制流。...

简单讲解Python中的字符串与字符串的输入输出

字符串 字符串用''或者""括起来,如果字符串内部有‘或者",需要使用\进行转义 >>> print 'I\'m ok.' I'm ok. 转义字符\可以转义...

python读写配置文件操作示例

本文实例讲述了python读写配置文件操作。分享给大家供大家参考,具体如下: 在用编译型语言写程序的时候,很多时候用到配置文件,作为一个约定的规则,一般用 ini 文件作为配置文件,当然...

Python制作词云的方法

Python制作词云的方法

需求: 看到朋友圈有人发词云照片,感觉自己也可以玩一玩,于是乎借助wordcloud实现功能。 环境: MacOS 10.12 +Python 2.7 +Wordcloud Windo...