Живой график в Pypons matplotlib не обновляется - PullRequest
1 голос
/ 03 апреля 2020

Я строю своего рода измерительную систему на основе Arduino Nano, потому что она дешевая и маленькая. Он должен измерять ускорение, ток, крутящий момент и напряжение, о чем я не собираюсь спрашивать.

Короче говоря, датчики, подключенные к Arduino, являются измеряемыми значениями, которые я посылаю через USB на P C, а затем работаем над этим. Я сделал какое-то приложение в Python, которое довольно полно, но у меня проблема с обновлением графиков.

Я сделал свой Main.py, который делает что-то, с GUI сделано с QT Designer, где я встраивал matplotlib. Когда я пытаюсь построить случайные значения, и он доставляется в mplwidget.py (ниже), он работает правильно. Но когда я пытаюсь отправить некоторые данные в класс печати из моего Main, вся процедура работает (я проверил это, добавив несколько отпечатков после каждого шага), но визуально ничего не происходит.

Коды ниже, в виде вставки ссылки:

import PyQt5.QtWidgets as pq
import PyQt5.QtGui as qg
import threading
import time
import serial
import copy
import csv
import os.path
import types
import datetime
import string
import sys
import random
from gui import Ui_MainWindow, QtWidgets, MplWidget

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
w=MplWidget()

#tu pocedury
def start():
    t = threading.Thread(target=readThatSerial, args=(com,runThis), daemon=True)
    t.daemon=True
    t.start()

def potwierdz():
    global com
    com=ui.combo_COM.currentText()
    print(com)
    global pomiar
    pomiar=ui.combo_COM_2.currentText()

ui.setupUi(MainWindow)

#tu zdarzenia
ui.startButton.clicked.connect(start)
ui.PotwierdzButton.clicked.connect(potwierdz)
MainWindow.show()

#tu reszta
def readThatSerial(whichSerial, runRef):
    ser = serial.Serial(whichSerial, 38400, timeout=3)
    whole = ""
    numbers = types.SimpleNamespace()
    numbers.dataNumber = 0
    while(runRef):
        s = ser.read()
        if(len(s) > 0):
            try:
                whole += s.decode("utf-8")
            except Exception as e:
                print("probably decode error: " + str(e))

        lastStart = 0
        for i in range(len(whole)):
            if(whole[i] == "<"):
                data = whole[lastStart:i]
                handleCommand(data, numbers)
                numOfMeas = 0  
                newData = whole[i+1:]
                whole = copy.deepcopy(newData)
                lastStart = i+1

def handleCommand(data, numbers):
    global pomiar
    zm=float(pomiar)*10
    interwal=zm
    parts = data.split("&")
    numbers.dataNumber += 1
    if(numbers.dataNumber % interwal == 0):
        for i in range(len(parts)):    
            if ("=" in parts[i]):                  
                lol = parts[i].split("=")
                print("ai fund da dataaaa: " + parts[i])
                print("name of data " + lol[0])
                print("value of data " + lol[1])
                numbers.dataNumber = 0

        with open('plik.csv', 'a', encoding='utf-8', newline='') as csvfile:
            csvwriter = csv.writer(csvfile)
            teraz=datetime.datetime.now()
            tim =(teraz.strftime("%H:%M:%S.%f"))
            czas=list([tim])
            csvwriter.writerow(czas+parts)
            print(czas)
            ui.LCD_ax1.display(parts[0])
            ui.LCD_ay1.display(parts[1])
            ui.LCD_az1.display(parts[2])
            x=[random.randint(0, 10) for i in range(4)]
            w.update_plot(x)

if not os.path.isfile('plik.csv'):
    with open('plik.csv', 'a', encoding='utf-8', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(["t", 'a_x', 'a_y', 'a_z', ])
        csvwriter.writerow(["H:m:s:ms",'m/s^2', 'm/s^2', 'm/s^2'])

runThis = True
sys.exit(app.exec_())
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1373, 760)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.startButton = QtWidgets.QPushButton(self.centralwidget)
        self.startButton.setGeometry(QtCore.QRect(1170, 350, 181, 51))
        self.startButton.setObjectName("startButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(750, 0, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label.setFont(font)
        self.label.setMouseTracking(True)
        self.label.setTextFormat(QtCore.Qt.RichText)
        self.label.setScaledContents(False)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(750, 80, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.LCD_U = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_U.setGeometry(QtCore.QRect(750, 30, 191, 41))
        self.LCD_U.setObjectName("LCD_U")
        self.LCD_I1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_I1.setGeometry(QtCore.QRect(750, 120, 191, 41))
        self.LCD_I1.setObjectName("LCD_I1")
        self.LCD_I2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_I2.setGeometry(QtCore.QRect(750, 210, 191, 41))
        self.LCD_I2.setObjectName("LCD_I2")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(750, 170, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(750, 260, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.LCD_I3 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_I3.setGeometry(QtCore.QRect(750, 290, 191, 41))
        self.LCD_I3.setObjectName("LCD_I3")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setGeometry(QtCore.QRect(960, 260, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_10.setFont(font)
        self.label_10.setObjectName("label_10")
        self.LCD_Moment = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_Moment.setGeometry(QtCore.QRect(960, 290, 191, 41))
        self.LCD_Moment.setObjectName("LCD_Moment")
        self.MplWidget = MplWidget(self.centralwidget)
        self.MplWidget.setGeometry(QtCore.QRect(10, 10, 731, 701))
        self.MplWidget.setObjectName("MplWidget")
        self.combo_COM = QtWidgets.QComboBox(self.centralwidget)
        self.combo_COM.setGeometry(QtCore.QRect(1170, 310, 181, 22))
        self.combo_COM.setObjectName("combo_COM")
        self.combo_COM.addItem("")
        self.combo_COM.addItem("")
        self.combo_COM.addItem("")
        self.combo_COM.addItem("")
        self.combo_COM.addItem("")
        self.combo_COM_2 = QtWidgets.QComboBox(self.centralwidget)
        self.combo_COM_2.setGeometry(QtCore.QRect(750, 370, 181, 22))
        self.combo_COM_2.setObjectName("combo_COM_2")
        self.combo_COM_2.addItem("")
        self.combo_COM_2.addItem("")
        self.combo_COM_2.addItem("")
        self.combo_COM_2.addItem("")
        self.combo_COM_2.addItem("")
        self.combo_COM_2.addItem("")
        self.label_11 = QtWidgets.QLabel(self.centralwidget)
        self.label_11.setGeometry(QtCore.QRect(1170, 270, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        self.label_11.setFont(font)
        self.label_11.setObjectName("label_11")
        self.label_13 = QtWidgets.QLabel(self.centralwidget)
        self.label_13.setGeometry(QtCore.QRect(750, 330, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        self.label_13.setFont(font)
        self.label_13.setObjectName("label_13")
        self.label_14 = QtWidgets.QLabel(self.centralwidget)
        self.label_14.setGeometry(QtCore.QRect(1170, 170, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_14.setFont(font)
        self.label_14.setObjectName("label_14")
        self.LCD_az2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_az2.setGeometry(QtCore.QRect(1170, 210, 191, 41))
        self.LCD_az2.setObjectName("LCD_az2")
        self.LCD_ax1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_ax1.setGeometry(QtCore.QRect(960, 30, 191, 41))
        self.LCD_ax1.setObjectName("LCD_ax1")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(960, 0, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.LCD_ay1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_ay1.setGeometry(QtCore.QRect(960, 120, 191, 41))
        self.LCD_ay1.setObjectName("LCD_ay1")
        self.LCD_ay2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_ay2.setGeometry(QtCore.QRect(1170, 120, 191, 41))
        self.LCD_ay2.setObjectName("LCD_ay2")
        self.LCD_ax2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_ax2.setGeometry(QtCore.QRect(1170, 30, 191, 41))
        self.LCD_ax2.setObjectName("LCD_ax2")
        self.label_15 = QtWidgets.QLabel(self.centralwidget)
        self.label_15.setGeometry(QtCore.QRect(960, 90, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_15.setFont(font)
        self.label_15.setObjectName("label_15")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(1170, 80, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(1170, 0, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_6.setFont(font)
        self.label_6.setMouseTracking(True)
        self.label_6.setTextFormat(QtCore.Qt.RichText)
        self.label_6.setScaledContents(False)
        self.label_6.setObjectName("label_6")
        self.LCD_az1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.LCD_az1.setGeometry(QtCore.QRect(960, 210, 191, 41))
        self.LCD_az1.setObjectName("LCD_az1")
        self.label_16 = QtWidgets.QLabel(self.centralwidget)
        self.label_16.setGeometry(QtCore.QRect(960, 180, 191, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        self.label_16.setFont(font)
        self.label_16.setObjectName("label_16")
        self.PotwierdzButton = QtWidgets.QPushButton(self.centralwidget)
        self.PotwierdzButton.setGeometry(QtCore.QRect(964, 350, 201, 51))
        self.PotwierdzButton.setObjectName("PotwierdzButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1373, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.startButton.setText(_translate("MainWindow", "Start"))
        self.label.setText(_translate("MainWindow", "Napięcie"))
        self.label_2.setText(_translate("MainWindow", "Prąd 1"))
        self.label_9.setText(_translate("MainWindow", "Prąd 2"))
        self.label_3.setText(_translate("MainWindow", "Prąd 3"))
        self.label_10.setText(_translate("MainWindow", "Moment"))
        self.combo_COM.setItemText(0, _translate("MainWindow", "COM1"))
        self.combo_COM.setItemText(1, _translate("MainWindow", "COM2"))
        self.combo_COM.setItemText(2, _translate("MainWindow", "COM3"))
        self.combo_COM.setItemText(3, _translate("MainWindow", "COM4"))
        self.combo_COM.setItemText(4, _translate("MainWindow", "COM5"))
        self.combo_COM_2.setItemText(0, _translate("MainWindow", "0.1"))
        self.combo_COM_2.setItemText(1, _translate("MainWindow", "0.2"))
        self.combo_COM_2.setItemText(2, _translate("MainWindow", "0.5"))
        self.combo_COM_2.setItemText(3, _translate("MainWindow", "1"))
        self.combo_COM_2.setItemText(4, _translate("MainWindow", "2"))
        self.combo_COM_2.setItemText(5, _translate("MainWindow", "5"))
        self.label_11.setText(_translate("MainWindow", "COM A"))
        self.label_13.setText(_translate("MainWindow", "Interwał pomiarowy"))
        self.label_14.setText(_translate("MainWindow", "a_z 2"))
        self.label_4.setText(_translate("MainWindow", "a_x 1"))
        self.label_15.setText(_translate("MainWindow", "a_y 1"))
        self.label_5.setText(_translate("MainWindow", "a_y 2"))
        self.label_6.setText(_translate("MainWindow", "a_x 2"))
        self.label_16.setText(_translate("MainWindow", "a_z 1"))
        self.PotwierdzButton.setText(_translate("MainWindow", "Potwierdź ustawienia"))
from mplwidget import MplWidget


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
from __future__ import unicode_literals
import sys
import os
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class MplWidget(MyMplCanvas):

    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)        

    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')

    def update_plot(self,x):
        l = x
        print(l)
        print(x)
        self.axes.cla()
        print("a")
        self.axes.plot([0, 1, 2, 3], l, 'r')
        print("b")
        self.draw()
        print("c")


Есть идеи? Пожалуйста?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...