可以帮我写一个接收串口数据的同时可以将数据写入excel表,同时又可以实时绘制数据折线图的python代码吗?要求绘制的折线图能在pyqt5的ui界面上实时显示
时间: 2024-04-23 14:22:34 浏览: 17
可以的,以下是样例代码,你可以根据自己的需求进行修改:
```python
import sys
import serial
import threading
import time
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout
from PyQt5.QtGui import QIcon, QPen, QPainter
from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal, QObject, QThread
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class SerialThread(QThread):
received_data = pyqtSignal(float)
def __init__(self, parent=None):
super(SerialThread, self).__init__(parent)
self.port = serial.Serial(port='COM1', baudrate=9600)
self.is_running = False
def run(self):
self.is_running = True
while self.is_running:
data = self.port.readline().decode('utf-8').strip()
if data:
self.received_data.emit(float(data))
def stop(self):
self.is_running = False
self.port.close()
class ExcelThread(QThread):
def __init__(self, parent=None):
super(ExcelThread, self).__init__(parent)
self.is_running = False
def run(self):
self.is_running = True
while self.is_running:
# 读取串口数据
data = ser_port.readline().decode('utf-8').strip()
if data:
# 将数据写入excel表
df = pd.DataFrame({'data': [data]})
df.to_excel('data.xlsx', index=False, header=False)
def stop(self):
self.is_running = False
class PlotWidget(QWidget):
def __init__(self, parent=None):
super(PlotWidget, self).__init__(parent)
self.data = []
self.plot_lock = threading.Lock()
self.figure = plt.Figure()
self.canvas = FigureCanvas(self.figure)
self.ax = self.figure.add_subplot(111)
self.ax.set_xlabel('Time')
self.ax.set_ylabel('Data')
self.ax.set_title('Real-time Plot')
self.line, = self.ax.plot(self.data, 'r-')
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
self.setLayout(vbox)
def update_plot(self, new_data):
self.plot_lock.acquire()
self.data.append(new_data)
self.line.set_ydata(self.data)
self.ax.relim()
self.ax.autoscale_view()
self.canvas.draw()
self.plot_lock.release()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('Serial Plot')
self.serial_thread = SerialThread()
self.serial_thread.received_data.connect(self.update_plot)
self.excel_thread = ExcelThread()
self.excel_thread.start()
self.plot_widget = PlotWidget()
self.setCentralWidget(self.plot_widget)
self.serial_thread.start()
def closeEvent(self, event):
self.serial_thread.stop()
self.excel_thread.stop()
event.accept()
@pyqtSlot(float)
def update_plot(self, data):
self.plot_widget.update_plot(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这个样例代码中,一个线程用于接收串口数据,一个线程用于将数据写入Excel表中。同时,画图部分使用matplotlib来实现,将画图部分的widget嵌入到了PyQt5的UI界面中。串口数据接收和Excel写入部分可以根据自己的需求进行修改。在使用时,需要将COM1改成自己的串口号,同时需要安装pandas和matplotlib模块。