通過(guò)兩個(gè)進(jìn)程分別讀寫(xiě)串口,并把發(fā)送與接收到的內(nèi)容記錄在blog中,收到q時(shí)程序結(jié)束并退出

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名稱為當(dāng)前時(shí)間
self.rfname='r'+fname #接收blog名稱
self.sfname='s'+fname #發(fā)送blog名稱
self.thread_read= None
self.thread_send=None
def waiting(self):
# 等待event停止標(biāo)志
if not self.waitEnd is None:
self.waitEnd.wait()
def start(self):
#開(kāi)串口以及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;
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
網(wǎng)站題目:Python3實(shí)現(xiàn)串口兩進(jìn)程同時(shí)讀寫(xiě)-創(chuàng)新互聯(lián)
分享鏈接:http://www.chinadenli.net/article26/iiccg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、ChatGPT、域名注冊(cè)、全網(wǎng)營(yíng)銷推廣、定制網(wǎng)站、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容