这篇博客主要记录一下PyQT多线程串口的主要代码分析,文末会有工程的源代码文件
首先,从PyCharm启动QtDesigner
之前给客户做的上位机,保密起见,删减了大部分的框图构件,但不影响本篇串口教程
QtDesigner界面如下:
忽略 添加数据以及表格数据显示,这里用不到
着重讲一下类的构成
新建一个串口类SerialThread,继承自QtCore.QThread,实现全部的串口收发功能
class SerialThread(QtCore.QThread):
dataReadoutSignal = pyqtSignal(str)
def __init__(self, parent = None, portName = 'COM3', baudrate = 9600, parity = 'N', bytesize = 8, stopbits = 1, timeout = None):
super(SerialThread, self).__init__(parent)
self.m_serialPort = serial.Serial()
self.m_serialPort.port = portName
self.m_serialPort.baudrate = baudrate
self.m_serialPort.parity = parity
self.m_serialPort.bytesize = bytesize
self.m_serialPort.stopbits = stopbits
self.m_serialPort.timeout = timeout
self.OpenScom()
def OpenScom(self):
try:
self.m_serialPort.open()
self.m_serialPort.setRTS(True)
self.m_serialPort.setDTR(True)
except Exception as ex:
print(ex)
return ex
def ScomSendOneData(self,datain):
if isinstance(datain,int):
listTemp = []
listTemp.append(datain)
d = bytes(listTemp)
self.m_serialPort.write(d)
else:
if isinstance(datain,str):
d = datain.encode('utf-8')
self.m_serialPort.write(d)
def ScomGetintData(self):
n = self.m_serialPort.inWaiting()
if n:
data = self.m_serialPort.read(n).hex()
#writefile
print(data)
def ScomGetstrData(self):
if self.m_serialPort.is_open:
n = self.m_serialPort.inWaiting()