带有tkinter GUI和matplotlib的Arduino(pySerial)

2024-09-26 04:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图显示一些用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', font = ('Verdana', 12), width = 12, 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)

Tags: selfmasterdataplotdeffigaxstart