python创建串口调试助手
时间: 2023-12-30 21:24:29 浏览: 91
以下是一个简单的Python串口调试助手的示例代码:
```python
import sys
import serial
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox, QTextEdit
from PyQt5.QtCore import QThread, pyqtSignal
class SerialThread(QThread):
data_arrive_signal = pyqtSignal()
def __init__(self, ser=None):
super().__init__()
self.ser = ser
self.data = ''
def run(self):
while True:
if self.ser and self.ser.in_waiting:
self.data += self.ser.read_all().decode('gbk')
print(self.data)
self.data_arrive_signal.emit()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.serial_port = None
self.serial_thread = None
self.combo_box = QComboBox(self)
self.combo_box.currentIndexChanged.connect(self.connect_serial)
self.text_edit = QTextEdit(self)
self.init_ui()
def init_ui(self):
self.setWindowTitle("Serial Debug Assistant")
self.setGeometry(100, 100, 400, 300)
self.combo_box.setGeometry(10, 10, 200, 30)
self.text_edit.setGeometry(10, 50, 380, 240)
self.show()
def connect_serial(self, index):
if self.serial_port:
self.serial_port.close()
port_name = self.combo_box.itemText(index)
try:
self.serial_port = serial.Serial(port_name, 9600)
self.serial_thread = SerialThread(self.serial_port)
self.serial_thread.data_arrive_signal.connect(self.update_text_edit)
self.serial_thread.start()
except serial.SerialException:
print("Failed to connect to serial port")
def update_text_edit(self):
self.text_edit.setText(self.serial_thread.data)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
这个示例代码使用了PyQt5库来创建一个简单的串口调试助手。它包括一个下拉框用于选择串口,一个文本编辑框用于显示接收到的数据。当选择串口后,程序会自动连接到选定的串口,并在接收到数据时更新文本编辑框。
阅读全文