首页 > 解决方案 > PyQtGraph 实时绘制多行数据

问题描述

我正在尝试在 PyQtGraph 中绘制来自 arduino 的多行数据。我希望代码本身能够识别它必须绘制多少行数据,但目前我在 PyQtGraph 中看不到任何数据。这是我到目前为止尝试过的代码。

from PyQt5 import QtWidgets, QtCore
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys 
import os
import serial
import numpy as np


class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.graphWidget.plotItem.showGrid(x=True, y=True, alpha=0.5)

        self.setCentralWidget(self.graphWidget)
        self.ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 9600) 
        self.x1 = np.array([])
        self.y1 = np.array([])
        self.xp = np.array([])
        self.yp = np.array([])
        self.dateien = 0 
        self.count = 0

        self.graphWidget.setBackground('w')

        self.timer = QtCore.QTimer()
        self.timer.setInterval(1)
        self.timer.timeout.connect(self.get_Data)
        self.timer.start()

        pen = pg.mkPen(color=(255, 0, 0), width=20)
        self.data_line =  self.graphWidget.plot(self.xp, self.yp, pen=pen)

    def plot(self, xp, yp):
        self.data_line.setData(xp, yp)

    def get_Data(self): 
        self.data = self.ser.readline()
        try:
            self.count = self.count + 1
            self.x1 = np.append(self.x1, self.count)
            self.decoded_data = str(self.data[0:len(self.data)-2].decode("utf-8"))
            self.dataArray = self.decoded_data.split()
            array_length = len(self.dataArray)
            for i in range(array_length): 
                 self.dateien = self.dataArray[i]
                 self.y1 = np.append(self.y1, float(self.dateien))
                 print(self.x1.shape, self.y1.shape)
                 self.data_line.setData(self.x1, self.y1)
        except (UnicodeDecodeError): 
             print("Error")

app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

“UnicodeDecodeError”出现在第一次读取串行数据时。我当前的输出如下所示:

Exception: X and Y arrays must be the same shape--got (122,) and (121,).

最后它应该看起来像 arduino 绘图仪。你有什么主意吗?

标签: pythonarduinopyqtgraph

解决方案


推荐阅读