简体   繁体   English

如何在matplotlib折线图中从txt文件中获取plot数据实时数据

[英]How to plot data real time data from a txt file in a matplotlib line graph

I have an ultrasonic sensor that writes the distance in a txt file, I want to get that data and plot it on a line graph in real time but I can't find a way to do it.我有一个将距离写入 txt 文件的超声波传感器,我想实时获取该数据和 plot 折线图,但我找不到方法。

What I have done till now is that it would read the file but it never shows the data.到目前为止我所做的是它会读取文件但它从不显示数据。

sensor.py传感器.py

import RPi.GPIO as GPIO
import time


GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)

TRIG = 23
ECHO = 24

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

GPIO.output(TRIG, True)
GPIO.output(TRIG,False)

def get_distance():
    GPIO.output(TRIG, True)
    time.sleep(0.0001)
    GPIO.output(TRIG, False)
        
    while GPIO.input(ECHO) == False:
        start = time.time()
        
    while GPIO.input(ECHO) == True:
        end = time.time()
        
    sig_time = end - start

    distance = sig_time/0.000058
    
    print('Distance: {} cm'.format(round(distance)))
    return distance
    
while True:
    distance = get_distance()
    data = round(distance)
    
    output = open("front sensor distance.txt", "w")
    output.write(str(data))
    time.sleep(2)
    output.close()

Whenever I run the code the distance gets deleted instantly and does not wait for time.sleep(2)每当我运行代码时,距离都会立即被删除并且不会等待time.sleep(2)

First of all, make sure that the code that ultrasonic uses to write data to file is not buffering writes and writes to file instantly by forcing it to flush after every write output.flush() , I edited your code to do that and also changed it to append to file instead of removing all old data with each write also I made it to save time with each write to use it in the graph.首先,确保超声波用于将数据写入文件的代码不会通过在每次写入output.flush()后强制刷新来立即缓冲写入和写入文件,我编辑了你的代码来做到这一点并且也改变了它到 append 到文件而不是每次写入都删除所有旧数据我也这样做是为了节省每次写入的time以在图中使用它。

start_time = time.time()

while True:
    output = open("front sensor distance.txt", "a")
    output.write(str(round(time.time()-start_time))+","+str(round(get_distance()))+"\n")
    time.sleep(2)
    output.flush()

then you can use this code sample which reads data from the file every 1 second and updates the graph in real-time.那么您可以使用此代码示例,它每 1 秒从文件中读取一次数据并实时更新图形。

I tried to write it as close to your description as possible where the data file contains time,distance in each line separated by a comma.我试着把它写得尽可能接近你的描述,其中数据文件包含time,distance用逗号分隔。

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

def animate(i):
    file_data = open("front sensor distance.txt","r").read()
    dataArray = file_data.split('\n')
    time = []
    distance = []
    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            time.append(float(x))
            distance.append(float(y))
    ax.clear()
    ax.plot(time,distance)

def Main():
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()
    print("done")

Main()

I don't have the hardware you have to test with so I made distance function return random numbers on my machine to simulate your experience.我没有你必须测试的硬件,所以我在我的机器上设置了distance function 返回随机数来模拟你的体验。 and running both files will result in the following real-time graph运行这两个文件将产生以下实时图表

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM