pyqt5界面设计串口发送数据,停止发送数据,刷新串口代码
时间: 2023-11-08 10:02:52 浏览: 204
下面是一个简单的使用PyQt5实现串口通信的界面设计代码,其中包括了发送数据、停止发送数据以及刷新串口的功能:
``` python
import sys
import serial
from PyQt5.QtCore import QIODevice, QSerialPort, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit
class SerialThread(QThread):
data_received = pyqtSignal(str)
def __init__(self, port, baudrate):
super(SerialThread, self).__init__()
self.port = port
self.baudrate = baudrate
self.is_running = True
def __del__(self):
self.is_running = False
def run(self):
ser = serial.Serial(self.port, self.baudrate)
while self.is_running:
if ser.in_waiting:
data = ser.readline().decode()
self.data_received.emit(data)
ser.close()
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Serial Communication")
self.resize(600, 400)
# Create widgets
self.text_edit_recv = QTextEdit(self)
self.text_edit_recv.setGeometry(10, 10, 580, 180)
self.text_edit_send = QTextEdit(self)
self.text_edit_send.setGeometry(10, 200, 400, 180)
self.btn_send = QPushButton('Send', self)
self.btn_send.setGeometry(430, 200, 80, 30)
self.btn_send.clicked.connect(self.send_data)
self.btn_stop = QPushButton('Stop', self)
self.btn_stop.setGeometry(520, 200, 80, 30)
self.btn_stop.clicked.connect(self.stop_sending)
self.btn_refresh = QPushButton('Refresh', self)
self.btn_refresh.setGeometry(430, 250, 170, 30)
self.btn_refresh.clicked.connect(self.refresh_ports)
# Initialize variables
self.port = None
self.baudrate = 9600
self.serial_thread = None
self.is_sending = False
def send_data(self):
if not self.is_sending:
self.port.write(self.text_edit_send.toPlainText().encode())
self.is_sending = True
def stop_sending(self):
self.is_sending = False
def refresh_ports(self):
port_list = [port.device for port in QSerialPortInfo.availablePorts()]
print("Available ports:", port_list)
def open_serial_port(self):
if not self.port:
port_name = "COM6" # Replace with the actual port name
self.port = serial.Serial(port_name, self.baudrate)
self.serial_thread = SerialThread(port_name, self.baudrate)
self.serial_thread.data_received.connect(self.display_data)
self.serial_thread.start()
def display_data(self, data):
self.text_edit_recv.append(data)
def closeEvent(self, event):
if self.port:
self.port.close()
if self.serial_thread:
del self.serial_thread
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在该示例代码中,我们使用了PyQt5中的QSerialPort模块来实现串口通信。SerialThread类继承自QThread,用于在后台线程中读取串口数据;MainWindow类继承自QMainWindow,用于创建GUI界面和处理相关事件。界面中包括了一个用于显示接收数据的文本框、一个用于输入发送数据的文本框、一个用于发送数据的按钮、一个用于停止发送数据的按钮以及一个用于刷新串口的按钮。
阅读全文