1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| from PyQt5 import QtWidgets, QtCore, QtSerialPort
class SerialAssistant(QtWidgets.QWidget): def __init__(self): super().__init__()
self.serial = QtSerialPort.QSerialPort() self.port_combo = QtWidgets.QComboBox() self.baudrate_combo = QtWidgets.QComboBox() self.open_button = QtWidgets.QPushButton('打开串口') self.close_button = QtWidgets.QPushButton('关闭串口') self.send_button = QtWidgets.QPushButton('发送') self.receive_text = QtWidgets.QTextEdit()
self.init_ui()
self.open_button.clicked.connect(self.open_serial) self.close_button.clicked.connect(self.close_serial) self.send_button.clicked.connect(self.send_data) self.serial.readyRead.connect(self.receive_data)
def init_ui(self): layout = QtWidgets.QVBoxLayout() form_layout = QtWidgets.QFormLayout()
ports = QtSerialPort.QSerialPortInfo.availablePorts() for port in ports: self.port_combo.addItem(port.portName())
baudrates = ['1200', '2400', '4800', '9600', '19200', '38400', '57600', '115200'] for baudrate in baudrates: self.baudrate_combo.addItem(baudrate)
form_layout.addRow('串口:', self.port_combo) form_layout.addRow('波特率:', self.baudrate_combo)
layout.addLayout(form_layout) layout.addWidget(self.open_button) layout.addWidget(self.close_button) layout.addWidget(self.send_button) layout.addWidget(QtWidgets.QLabel('接收数据:')) layout.addWidget(self.receive_text)
self.setLayout(layout) self.setWindowTitle('串口调试助手')
def open_serial(self): port_name = self.port_combo.currentText() baudrate = int(self.baudrate_combo.currentText())
self.serial.setPortName(port_name) self.serial.setBaudRate(baudrate) self.serial.setDataBits(QtSerialPort.QSerialPort.Data8) self.serial.setParity(QtSerialPort.QSerialPort.NoParity) self.serial.setStopBits(QtSerialPort.QSerialPort.OneStop) self.serial.setFlowControl(QtSerialPort.QSerialPort.NoFlowControl)
if self.serial.open(QtCore.QIODevice.ReadWrite): QtWidgets.QMessageBox.information(self, '提示', '串口打开成功') else: QtWidgets.QMessageBox.warning(self, '错误', '串口打开失败')
def close_serial(self): self.serial.close() QtWidgets.QMessageBox.information(self, '提示', '串口已关闭')
def send_data(self): data = self.receive_text.toPlainText().encode() self.serial.write(data)
def receive_data(self): data = self.serial.readAll() self.receive_text.append(data.data().decode())
if __name__ == '__main__': app = QtWidgets.QApplication([]) window = SerialAssistant() window.show() app.exec_()
|