import serial
import threading
class ComClass:
def __init__(self,port,baud):
self.port = port
self.baud = baud
self.comSerial = None
self.run = False
self.open()
if self.run:
self.thread1 = threading.Thread(target=self.receiveData)
self.thread2 = threading.Thread(target=self.sendData)
self.thread1.start()
self.thread2.start()
self.thread1.join()
self.thread2.join()
self.close()
def open(self):
try:
self.comSerial = serial.Serial(self.port,self.baud)
self.run = True
print("打开串口成功")
except:
print("打开串口失败")
self.close()
def close(self):
self.comSerial.close()
print("关闭串口")
def sendData(self):
print("sendData")
while self.run:
send_data = input()
if send_data:
self.comSerial.write(send_data.encode('UTF-8'))
print('发送数据:%s' % send_data)
if send_data == "break":
print("发送数据线程结束")
self.run = False
def receiveData(self):
print("receiveData")
while self.run:
receive_data = self.comSerial.read(self.comSerial.inWaiting()).decode("gbk")
if receive_data:
print('接收数据:%s' % receive_data)
if receive_data == "break":
print("接收数据线程结束")
self.run = False
a = ComClass('COM2',9600)
input("输入任意字符结束程序!")
python 串口通信多线程程序
于 2022-05-06 11:48:37 首次发布