pyqt5写的串口调试助手 示例代码
时间: 2023-07-07 18:04:22 浏览: 140
下面是一个简单的 PyQT5 串口调试助手示例代码:
```python
import sys
import serial
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox, QPushButton, QTextEdit, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 初始化串口
self.serial_port = serial.Serial()
# 设置窗口大小和标题
self.setGeometry(100, 100, 400, 400)
self.setWindowTitle('Serial Port Assistant')
# 下拉框控件,用于选择串口号和波特率
self.combo_box_port = QComboBox(self)
self.combo_box_port.move(20, 20)
self.combo_box_port.resize(150, 30)
self.combo_box_port.addItems(['COM{}'.format(i + 1) for i in range(256)])
self.combo_box_baud_rate = QComboBox(self)
self.combo_box_baud_rate.move(200, 20)
self.combo_box_baud_rate.resize(150, 30)
self.combo_box_baud_rate.addItems(['9600', '115200', '230400', '460800'])
# 打开和关闭串口按钮
self.btn_open = QPushButton('Open', self)
self.btn_open.move(20, 70)
self.btn_open.clicked.connect(self.open_serial_port)
self.btn_close = QPushButton('Close', self)
self.btn_close.move(200, 70)
self.btn_close.clicked.connect(self.close_serial_port)
# 文本框控件,用于显示收发数据
self.text_receive = QTextEdit(self)
self.text_receive.move(20, 120)
self.text_receive.resize(350, 200)
self.text_send = QTextEdit(self)
self.text_send.move(20, 340)
self.text_send.resize(350, 40)
# 发送按钮
self.btn_send = QPushButton('Send', self)
self.btn_send.move(280, 390)
self.btn_send.clicked.connect(self.send_data)
# 状态栏,用于显示串口状态
self.status_bar = QLabel(self)
self.status_bar.move(20, 390)
self.status_bar.resize(200, 20)
self.status_bar.setText('Serial Port Closed')
def open_serial_port(self):
# 获取串口号和波特率
port = self.combo_box_port.currentText()
baud_rate = int(self.combo_box_baud_rate.currentText())
# 打开串口
self.serial_port.port = port
self.serial_port.baudrate = baud_rate
self.serial_port.open()
# 更新状态栏和按钮状态
self.status_bar.setText('Serial Port Opened')
self.btn_open.setEnabled(False)
self.btn_close.setEnabled(True)
# 监听串口数据
self.serial_port.timeout = 0.1
self.serial_port.bytesize = 8
self.serial_port.parity = 'N'
self.serial_port.stopbits = 1
self.serial_port.xonxoff = False
self.serial_port.rtscts = False
self.serial_port.dsrdtr = False
self.serial_port.flushInput()
self.serial_port.flushOutput()
while True:
try:
data = self.serial_port.readline().decode('utf-8')
except:
break
if data:
self.text_receive.append(data)
def close_serial_port(self):
# 关闭串口
self.serial_port.close()
# 更新状态栏和按钮状态
self.status_bar.setText('Serial Port Closed')
self.btn_open.setEnabled(True)
self.btn_close.setEnabled(False)
def send_data(self):
# 发送数据
data = self.text_send.toPlainText().encode('utf-8')
self.serial_port.write(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这个示例程序实现了串口的打开和关闭,以及收发数据,并且使用了 PyQT5 的一些常用控件,如下拉框、文本框、按钮和状态栏等。你可以根据自己的需求进行修改和扩展。
阅读全文