如何解决GUI + matplotlib:读取传感器,并实时更新图形标签问题
简短版本...我还不能发布图片,但这是此带有传感器运行的脚本的简短gif。 y轴是距离(0-200厘米),高线图是到我天花板的距离。如果您仔细观察该图,您会注意到x轴刻度线移动,并且在gif的开头和结尾处,会出现一秒钟的空白灰色空间。那就是我在...方面遇到的问题
https://thumbs.gfycat.com/LastingHarshKiwi-size_restricted.gif
我在树莓派4上,我把一个超声波距离传感器连接到了gpio中。如果您想复制项目并运行脚本,请参阅问题底部的详细信息(我从freenove入门工具包获得了代码和组件)。我还想提及我对编码非常陌生的内容,感谢所有帮助,并抱歉,如果我发慢或不了解某些内容。
我主要担心的问题是希望获得帮助:)
- 我无法将时间戳记留在同一地点。随着图表更新,Id也喜欢标签更新的时间。但不要动。他们目前确实会更新,但会移动。我想在开始,中间和结束处放置3个时间戳。
- 我也不知道将gpio.cleanup()放在哪里以使其正常工作。
另外,由于可能仍然会出现,而且我正在学习:
- 我用2个csv文件编写了此文件,而不是仅读取1个文件的最后20行。希望我能做到这一点,当我追加阅读内容时,我不会阅读 growLogData.csv 中的每一行。几周后,此文件将很大。 问-这是我的想法吗?还是您必须阅读每一行才能添加?
- 最后,我不确定这是否是编写此代码的最有效方法,并且我愿意提出改进建议。最终产品将运行许多传感器,并且 growLogData.csv 文件将有很多行,因此id(例如加载时间)应尽可能快(显然)
TESTERv2.py
import matplotlib
import tkinter as tk
matplotlib.use("TkAgg")
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.animation as animation
import matplotlib.dates as mdates
from matplotlib import style
import RPi.GPIO as GPIO
import pandas as pd
import numpy as np
import time
import csv
#from scipy.interpolate import spline
trigPin = 16
echoPin = 18
MAX_DISTANCE = 220 # define the maximum measuring distance,unit: cm
timeOut = MAX_DISTANCE * 60 # calculate timeout according to the maximum measuring distance
GPIO.setwarnings(False) # I dont know where to put gpio cleanup,so for now i just cleared warnings====================
def pulseIn(pin,level,timeOut): # obtain pulse time of a pin under timeOut
t0 = time.time()
while GPIO.input(pin) != level:
if (time.time() - t0) > timeOut * 0.000001:
return 0
t0 = time.time()
while GPIO.input(pin) == level:
if (time.time() - t0) > timeOut * 0.000001:
return 0
pulseTime = (time.time() - t0) * 1000000
return pulseTime
def getSonar(): # get the measurement results: cm
GPIO.output(trigPin,GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(trigPin,GPIO.LOW)
pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut)
distance = pingTime * 340.0 / 2.0 / 10000.0
return distance
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(trigPin,GPIO.OUT) # set trigPin to OUTPUT mode
GPIO.setup(echoPin,GPIO.IN) # set echoPin to INPUT mode
style.use("ggplot") # matplotlib's graph style
# graph data ------------------------------------------------------------------
f = plt.Figure(dpi=75,tight_layout=True)
a = f.add_subplot(111)
dateparse = lambda x: pd.datetime.strptime(x,'$H:$M:$S')
def animate(e): # loop for graphing data -- contains dataframe,and dictionary item to get distance ===================
headers = ['date','time','distance']
SonarDataF = pd.read_csv('livegraph.csv',parse_dates=True,date_parser=dateparse,names=headers,skiprows=1)
distance = getSonar() # get distance
Epoch = time.time() # get date and time
timeObj = time.localtime(Epoch)
thedate = '%d-%d-%d' % (timeObj.tm_mon,timeObj.tm_mday,timeObj.tm_year)
thetime = '%d:%d:%d' % (timeObj.tm_hour,timeObj.tm_min,timeObj.tm_sec)
new_row = {'date': thedate,'time': thetime,'distance': distance} # adds row to bottom of csv
SonarDataF = SonarDataF.append(new_row,ignore_index=True)
num_rows = SonarDataF.shape[0] # limits rows allowed in graph csv
if num_rows > 20:
SonarDataF = SonarDataF.iloc[1:]
SonarDataF.to_csv('livegraph.csv',index=False) # saves updated dataframe to be loaded after loop
lognumbers = {'date': thedate,'distance': distance} # saves updated reading to full log
csv_file = "growLogData.csv"
try:
with open(csv_file,'a') as csvfile:
writer = csv.DictWriter(csvfile,fieldnames=headers)
for data in lognumbers:
writer.writerow(lognumbers)
except IOError:
print('fuck')
tim3 = SonarDataF['time'] # fetch dataframe for the graph
rTime = [datetime.strptime(t,'%H:%M:%S') for t in tim3]
rDist = SonarDataF['distance'].astype(float)
a.clear() # Clear the graphs,and replot with the following settings
a.grid(which="both")
a.grid(which='minor',alpha=0.3)
a.grid(which='major',alpha=0.6)
xmin = rTime[-20] # this takes away internal padding
xmax = rTime[-1]
a.set_xlim(xmin,xmax)
a.set_ylim(0,200)
a.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S')) # date formatter dunno if this is doing anything
a.axes.get_xaxis().set_visible(True)
a.set_autoscale_on(False)
# I couldn't get these to work. spline isn't recognised :S
# time_smooth = np.linspace(rTime.min(),rDist.max(),300)
# distance_smooth = spline(rTime,rDist)
a.plot(rTime,rDist,color="#ffffff")
a.legend(['Distance'])
class Window(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,**kwargs)
container = tk.Frame(self)
container.pack(side="top",fill="both",expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
self.frames = {}
frame = StartPage(container,self)
self.frames[StartPage] = frame
frame.grid(row=0,column=0,sticky="nsew")
self.show_frame(StartPage)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self,text='Test code')
label.pack(padx=10,pady=10)
graphsize = tk.Frame(self,width=600,height=400,background='#ffffff')
canvas = FigureCanvasTkAgg(f,graphsize)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH)
graphsize.pack()
graphsize.pack_propagate(False)
app = Window()
ani = animation.FuncAnimation(f,animate,interval=1000)
app.mainloop()
文件:
livegraph.csv (每次添加新行,第一行都会被删除)
date,time,distance
9-22-2020,15:25:0,42.84548759460449
9-22-2020,15:25:2,42.80495643615723
9-22-2020,15:25:3,44.7545051574707
9-22-2020,15:25:4,45.18008232116699
9-22-2020,15:25:5,48.43473434448242
9-22-2020,15:25:6,55.24396896362305
9-22-2020,15:25:7,62.59632110595703
9-22-2020,15:25:9,61.9194507598877
9-22-2020,15:25:10,61.12909317016602
9-22-2020,15:25:11,61.74111366271973
9-22-2020,15:25:12,60.87779998779297
9-22-2020,15:25:14,60.02259254455566
9-22-2020,15:25:15,65.00792503356935
9-22-2020,15:25:16,62.96515464782715
9-22-2020,15:25:17,68.91512870788574
9-22-2020,15:25:18,69.41366195678711
9-22-2020,15:25:20,70.35398483276367
9-22-2020,15:25:21,69.85950469970703
9-22-2020,15:25:22,161.80849075317386
9-22-2020,15:25:23,162.43672370910645
growLogData.csv (读数已添加到该文件中,但不能用于制图)
date,10:23:28,163.9080047607422
9-22-2020,10:23:29,163.90395164489746
构建此项目:
- 超声波传感器(HC-SR04)
- 1k电阻器(x3)
- 公对母GPIO跳线(x4)
- 实心线(x1)
- 面包板
- 扩展板
面包板上的树莓派设置: (您可能会注意到左侧的黑色和红色电线,那只是我的机箱风扇,运行至5v并接地。)
[我无法发布图片,因为我没有10个声誉]
vcc -> 5v
触发-> gpio 23
回声-> 1k电阻-> gpio 24
回声阻止器之后 -> 1k抵抗器-> 1k抵抗器-> 接地
gnd -> 地面
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。