python串口工具_使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
时间: 2023-12-29 17:03:00 浏览: 134
下面是一个简单的Python3+PyQT5+Pyserial实现串口工具的示例代码:
```python
import sys
import serial
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QComboBox, QTextEdit, QVBoxLayout, QHBoxLayout
class SerialTool(QWidget):
def __init__(self):
super().__init__()
self.serial = serial.Serial()
self.initUI()
def initUI(self):
self.portLabel = QLabel("Port:")
self.portComboBox = QComboBox()
self.refreshPorts()
self.baudrateLabel = QLabel("Baudrate:")
self.baudrateComboBox = QComboBox()
self.baudrateComboBox.addItems(["9600", "115200"])
self.openButton = QPushButton("Open")
self.openButton.clicked.connect(self.openSerial)
self.closeButton = QPushButton("Close")
self.closeButton.clicked.connect(self.closeSerial)
self.closeButton.setEnabled(False)
self.sendLabel = QLabel("Send:")
self.sendTextEdit = QTextEdit()
self.sendButton = QPushButton("Send")
self.sendButton.clicked.connect(self.sendData)
self.recvLabel = QLabel("Receive:")
self.recvTextEdit = QTextEdit()
self.recvTextEdit.setReadOnly(True)
portLayout = QHBoxLayout()
portLayout.addWidget(self.portLabel)
portLayout.addWidget(self.portComboBox)
baudrateLayout = QHBoxLayout()
baudrateLayout.addWidget(self.baudrateLabel)
baudrateLayout.addWidget(self.baudrateComboBox)
buttonLayout = QHBoxLayout()
buttonLayout.addWidget(self.openButton)
buttonLayout.addWidget(self.closeButton)
sendLayout = QHBoxLayout()
sendLayout.addWidget(self.sendLabel)
sendLayout.addWidget(self.sendTextEdit)
sendLayout.addWidget(self.sendButton)
recvLayout = QHBoxLayout()
recvLayout.addWidget(self.recvLabel)
recvLayout.addWidget(self.recvTextEdit)
mainLayout = QVBoxLayout()
mainLayout.addLayout(portLayout)
mainLayout.addLayout(baudrateLayout)
mainLayout.addLayout(buttonLayout)
mainLayout.addLayout(sendLayout)
mainLayout.addLayout(recvLayout)
self.setLayout(mainLayout)
self.setWindowTitle("Serial Tool")
self.show()
def refreshPorts(self):
self.portComboBox.clear()
ports = serial.tools.list_ports.comports()
for port, _, _ in ports:
self.portComboBox.addItem(port)
def openSerial(self):
port = self.portComboBox.currentText()
baudrate = int(self.baudrateComboBox.currentText())
self.serial.port = port
self.serial.baudrate = baudrate
try:
self.serial.open()
self.openButton.setEnabled(False)
self.closeButton.setEnabled(True)
except serial.SerialException:
pass
def closeSerial(self):
self.serial.close()
self.openButton.setEnabled(True)
self.closeButton.setEnabled(False)
def sendData(self):
data = self.sendTextEdit.toPlainText()
if data:
self.serial.write(data.encode("utf-8"))
def readData(self):
data = self.serial.readline().decode("utf-8")
self.recvTextEdit.append(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
serialTool = SerialTool()
sys.exit(app.exec_())
```
这个串口工具界面包含了选择串口、波特率、打开/关闭串口、发送数据和接收数据等功能,并且可以实时显示接收到的数据。你可以根据自己的实际需求进行修改和扩展。
阅读全文