带有tkinter GUI和Matplotlib的ArduinopySerial

问题描述

我试图显示一些通过Arduino获得的读数(在本例中,我只是在使用一个电位计)。问题在于我的程序无法检测锅的变化,从而导致在图形上连续显示。有没有办法解决它,还是我需要给它另一种方法?这是我创建的用于显示数据的类。

data = np.array([])
cond = False

def plot_start():
global cond
cond = True


def plot_stop():
global cond
cond = False

class Win3:
def __init__(self,master):
    self.master = master
    self.master.resizable(0,0)
    self.master.title('Anxiety test')
    self.master.geometry('1920x1080')
    # ===== Image background =====
    imageLogin = PhotoImage(file = 'testGUI.png')
    self.w = w = tk.Label(master,image = imageLogin)
    w.imageLogin = imageLogin
    # ===== Place of the elements =====
    w.pack(pady = 0,padx = 0)
    self.createWidgets()

# ===== Arduino reader =====
def plot_data(self):
    global cond,data
    if cond:
        a = self.s.readline()
        a.decode()
        if len(data) < 100:
            data = np.append(data,float(a[0:4]))
        else:
            data[0:99] = data[1:100]
            data[99] = float(a[0:4])
        self.linesx.set_xdata(np.arange(0,len(data)))
        self.linesx.set_ydata(data)
        self.canvas.draw()
    self.master.after(1,self.plot_data)

# ===== Figures for plot =====
def createWidgets(self):
    fig = Figure(figsize = (15,5))
    ax = fig.add_subplot(311)
    ay = fig.add_subplot(312)
    az = fig.add_subplot(313)
    # ===== Labels and grids =====
    ax.set_ylabel('Voltage1 [V]')
    ay.set_ylabel('Voltage2 [V]')
    az.set_ylabel('Voltage3 [V]')
    ax.grid()
    ay.grid()
    az.grid()
    # ===== Axis limits =====
    ax.set_xlim(0,150)
    ax.set_ylim(0,1024)
    ay.set_xlim(0,150)
    az.set_xlim(0,150)

    fig.tight_layout()

    # ===== Lines to plot =====
    self.linesx = ax.plot([],[])[0]
    self.linesy = ay.plot([],[])[0]
    self.linesz = az.plot([],[])[0]

    canvas = FigureCanvasTkAgg(fig,master = self.master)
    canvas.get_tk_widget().place(x = 170,y = 550,width = 1700,height = 450)
    canvas.draw()
    self.canvas = canvas
    # ===== Buttons to start or stop plots =====
    self.master.update()
    start = tk.Button(self.master,text = 'Start',font = ('Verdana',12),width = 12,command = lambda: plot_start())
    start.place(x = 250,y = 480)
    self.master.update()
    stop = tk.Button(self.master,text = 'Stop',command = lambda: plot_stop())
    stop.place(x = start.winfo_x() + start.winfo_reqwidth() + 20,y = 480)
    # ===== Arduino =====
    self.s = sr.Serial('COM1',9600)
    self.s.reset_input_buffer()
    self.master.after(1,self.plot_data)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)