Jun-06-2020, 11:25 AM
Hi,
I'm plotting a signal from an Arduino analog pin.
I'm able to plot it, however i cannot get to embed it into a tkinter window.
All i get is separated windows, one for the plot and another for tkinter.
Regards,
I'm plotting a signal from an Arduino analog pin.
I'm able to plot it, however i cannot get to embed it into a tkinter window.
All i get is separated windows, one for the plot and another for tkinter.
import serial
import time
import csv
import matplotlib
matplotlib.use("tkAgg")
import matplotlib.pyplot as plt
import numpy as np
from time import perf_counter
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
root = tk.Tk()
fig = Figure()
ax = fig.add_subplot(111)
# ax = plt.axes(xlim=(0,100),ylim=(120,150)); #displaying only 100 samples
ax.set_title('Serial Data')
ax.set_xlabel('Sample')
ax.set_ylabel('Pot1')
ax.set_xlim(0, 100)
ax.set_ylim(50, 1000)
ax.grid()
lines = ax.plot([], [])[0]
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.get_tk_widget().place(x=20, y=20, width=600, height=600)
canvas.draw()
ser = serial.Serial('COM4')
ser.flushInput()
plot_window = 20
y_var = np.array(np.zeros([plot_window]))
plt.ion()
fig, ax = plt.subplots()
line, = ax.plot(y_var)
while True:
try:
ser_bytes = ser.readline()
try:
decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
print(decoded_bytes)
except:
continue
with open("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([time.perf_counter(),decoded_bytes])
y_var = np.append(y_var,decoded_bytes)
y_var = y_var[1:plot_window+1]
line.set_ydata(y_var)
ax.relim()
ax.autoscale_view()
fig.canvas.draw()
fig.canvas.flush_events()
except:
print("Keyboard Interrupt")
break
root.mainloop()i appreciate your help.Regards,
