python串口工具_使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
时间: 2023-12-29 09:02:59 浏览: 202
下面是使用Python3+PyQT5+Pyserial实现简单的串口工具方法的示例代码:
``` python
import sys
import serial
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
from PyQt5.QtCore import QThread, pyqtSignal
class SerialThread(QThread):
received = pyqtSignal(str)
def __init__(self, port, baudrate):
super().__init__()
self.port = port
self.baudrate = baudrate
self.serial = None
def run(self):
try:
self.serial = serial.Serial(self.port, self.baudrate)
while True:
data = self.serial.readline().decode("utf-8")
if data:
self.received.emit(data)
except Exception as e:
print(e)
def write(self, data):
if self.serial:
self.serial.write(data.encode("utf-8"))
def close(self):
if self.serial:
self.serial.close()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Serial Tool")
self.setGeometry(100, 100, 800, 600)
self.text_edit = QTextEdit(self)
self.text_edit.setReadOnly(True)
self.setCentralWidget(self.text_edit)
open_action = QAction("Open", self)
open_action.setShortcut("Ctrl+O")
open_action.triggered.connect(self.open_file)
self.menuBar().addAction(open_action)
self.thread = SerialThread("COM1", 115200)
self.thread.received.connect(self.append_text)
self.thread.start()
def append_text(self, text):
self.text_edit.moveCursor(QtGui.QTextCursor.End)
self.text_edit.insertPlainText(text)
def open_file(self):
file_name, _ = QFileDialog.getOpenFileName(self, "Open File", "", "Text Files (*.txt)")
if file_name:
with open(file_name, "r") as f:
data = f.read()
self.thread.write(data)
def closeEvent(self, event):
self.thread.close()
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这个示例代码实现了一个简单的串口工具,可以实现打开串口、读取串口数据、发送数据等功能。其中SerialThread类用于在后台线程中读取串口数据,MainWindow类用于创建窗口并处理窗口事件。该代码可以根据需要进行修改和扩展。
阅读全文