python写一个串口助手
时间: 2023-12-12 22:34:10 浏览: 106
python串口助手
以下是一个简单的Python串口助手的实现,它使用了PyQt5库来实现GUI界面和串口通信功能:
```python
import sys
import serial
import serial.tools.list_ports
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QTextCursor
from ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.Com_Dict = {}
self.ser = serial.Serial()
self.timer = QTimer(self)
self.timer.timeout.connect(self.receive_data)
self.pushButton_open.clicked.connect(self.port_open)
self.pushButton_close.clicked.connect(self.port_close)
self.pushButton_send.clicked.connect(self.send_data)
self.pushButton_clear.clicked.connect(self.textBrowser_receive.clear)
self.port_check()
def port_check(self):
# 检测所有存在的串口,将信息存储在字典中
port_list = list(serial.tools.list_ports.comports())
self.comboBox_port.clear()
for port in port_list:
self.Com_Dict["%s" % port[0]] = "%s" % port[1]
self.comboBox_port.addItem(port[0])
# 无串口判断
if len(self.Com_Dict) == 0:
self.comboBox_port.addItem("无串口")
def port_open(self):
# 打开串口
self.ser.port = self.comboBox_port.currentText()
self.ser.baudrate = int(self.comboBox_baudrate.currentText())
self.ser.bytesize = int(self.comboBox_databit.currentText())
self.ser.stopbits = int(self.comboBox_stopbit.currentText())
self.ser.parity = self.comboBox_parity.currentText()
try:
self.ser.open()
except Exception as e:
QMessageBox.warning(self, "警告", str(e))
return None
if self.ser.isOpen():
self.pushButton_open.setEnabled(False)
self.pushButton_close.setEnabled(True)
self.comboBox_port.setEnabled(False)
self.comboBox_baudrate.setEnabled(False)
self.comboBox_databit.setEnabled(False)
self.comboBox_stopbit.setEnabled(False)
self.comboBox_parity.setEnabled(False)
self.timer.start(100)
def port_close(self):
# 关闭串口
self.timer.stop()
self.ser.close()
self.pushButton_open.setEnabled(True)
self.pushButton_close.setEnabled(False)
self.comboBox_port.setEnabled(True)
self.comboBox_baudrate.setEnabled(True)
self.comboBox_databit.setEnabled(True)
self.comboBox_stopbit.setEnabled(True)
self.comboBox_parity.setEnabled(True)
def send_data(self):
# 发送数据
if self.ser.isOpen():
send_data = (self.textEdit_send.toPlainText() + '\n').encode()
self.ser.write(send_data)
def receive_data(self):
# 接收数据
try:
num = self.ser.inWaiting()
except Exception as e:
self.timer.stop()
QMessageBox.warning(self, "警告", str(e))
return None
if num > 0:
data = self.ser.read(num)
self.textBrowser_receive.insertPlainText(data.decode())
self.textBrowser_receive.moveCursor(QTextCursor.End)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
阅读全文