import sys
import serial
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QPushButton, QVBoxLayout, QWidget
class SerialAssistant(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Serial Assistant")
self.setGeometry(100, 100, 400, 300)
self.serial_port = serial.Serial()
self.text_edit = QTextEdit()
self.connect_button = QPushButton("Connect")
self.send_button = QPushButton("Send")
layout = QVBoxLayout()
layout.addWidget(self.text_edit)
layout.addWidget(self.connect_button)
layout.addWidget(self.send_button)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.connect_button.clicked.connect(self.connect_serial)
self.send_button.clicked.connect(self.send_data)
def connect_serial(self):
if not self.serial_port.is_open:
self.serial_port.port = "COM1" # 设置串口号
self.serial_port.baudrate = 9600 # 设置波特率
self.serial_port.timeout = 1 # 设置超时时间
try:
self.serial_port.open()
self.text_edit.append("Serial port connected.")
except Exception as e:
self.text_edit.append("Failed to connect serial port: " + str(e))
else:
self.serial_port.close()
self.text_edit.append("Serial port disconnected.")
def send_data(self):
if self.serial_port.is_open:
data = "Hello, World!"
self.serial_port.write(data.encode()) # 发送数据
self.text_edit.append("Data sent: " + data)
else:
self.text_edit.append("Serial port is not connected.")
if __name__ == "__main__":
app = QApplication(sys.argv)
assistant = SerialAssistant()
assistant.show()
sys.exit(app.exec_())
|