from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal
import serial
import sys
class SerialThread(QThread):
data_signal = pyqtSignal(str) # 定义一个信号,用于发送串口数据
def __init__(self, port, baudrate, parent=None):
super(SerialThread, self).__init__(parent)
self.port = port
self.baudrate = baudrate
self.is_running = True
def run(self):
try:
ser = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=1)
while self.is_running:
if ser.in_waiting:
data = ser.readline().decode('utf-8').strip()
self.data_signal.emit(data) # 当有数据时,发射信号
except Exception as e:
QMessageBox.critical(None, 'Error', str(e))
finally:
ser.close()
def stop(self):
self.is_running = False
self.terminate()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.serial_thread = SerialThread('COM3', 9600)
self.init_ui()
self.serial_thread.data_signal.connect(self.on_data_received) # 连接信号槽
def init_ui(self):
self.setWindowTitle('串口数据采集')
self.button_start = QPushButton('开始')
self.button_start.clicked.connect(self.on_button_start_clicked)
self.button_stop = QPushButton('停止')
self.button_stop.clicked.connect(self.on_button_stop_clicked)
layout = QVBoxLayout()
layout.addWidget(self.button_start)
layout.addWidget(self.button_stop)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def on_button_start_clicked(self):
if not self.serial_thread.isRunning():
self.serial_thread.start()
self.button_start.setEnabled(False)
self.button_stop.setEnabled(True)
def on_button_stop_clicked(self):
self.button_start.setEnabled(True)
self.button_stop.setEnabled(False)
self.serial_thread.stop()
def on_data_received(self, data):
print(data) # 在这里处理接收到的数据
if __name__ == '__main__':
app = QApplic
评论已关闭