GUI + matplotlib:读取传感器,并实时更新图形标签问题

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-