Display graph of data from txt file

我怕爱的太早我们不能终老 提交于 2019-12-12 04:26:24

问题


I'm very new to Python. I'm using a Temperature sensor to read write data to a txt file. When I ran this code, it writes the temperature once, plots the graph and stops working until I close the figure.

import os
import glob
import datetime
import time
import csv

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pylab
from csv import reader
from dateutil import parser

mydate = datetime.datetime.now()

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28-051684d20cff')[0]
device_file = device_folder + '/w1_slave'


def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(5.0)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0

        #Write Temp data to csv file
        with open("Tempdata.txt", "a") as tempFile:
            tempFileWriter = csv.writer(tempFile)
            tempFileWriter.writerow([mydate,temp_f])

        print ("Temperature (\u2103) = ",temp_c)
        print ("Temperature (F) = ",temp_f)
        return temp_c, temp_f


while True:    
    print(read_temp())
    print ("--------------------------------------")
    fig = plt.figure("Temperature")
    ax1 = fig.add_subplot(1,1,1)
    plt.title("Temperature changes over Time")
    plt.xlabel("Time/hours")
    plt.ylabel("Temperature (\u2103)")

    def animate(i):

        pullData = open("Tempdata.txt","r").read()
        dataArray = pullData.split('\n')
        time = []
        temp = []
        for eachLine in dataArray:
            if len(eachLine)>1:
                x,y = eachLine.split(',')
                time.append(parser.parse(x))
                temp.append(int(float(y)))
        ax1.clear()
        ax1.plot(time,temp)
        plt.title("Temperature changes over Time")
        plt.xlabel("Time/hours")
        plt.ylabel("Temperature (\u2103)")
        fig.autofmt_xdate()

    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()
    time.sleep(2)

I edited the codes and it's logging data, but no longer displaying the graph. I'm using the SunFounder DS18B20 Temp sensor and modifying the codes so that it logs data into a local txt file and using the data in the txt file to graph it.

import os
import glob
import datetime
import time
import csv

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pylab
from csv import reader
from dateutil import parser

mydate = datetime.datetime.now()

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28-051684d20cff')[0]
device_file = device_folder + '/w1_slave'


fig = plt.figure("Temperature")
ax1 = fig.add_subplot(1,1,1)
plt.title("Temperature changes over Time")
plt.xlabel("Time/hours")
plt.ylabel("Temperature (\u2103)")


def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(5.0)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0

        #Write Temp data to csv file
        with open("Tempdata.txt", "a") as tempFile:
            tempFileWriter = csv.writer(tempFile)
            tempFileWriter.writerow([mydate,temp_f])

        print ("Temperature (\u2103) = ",temp_c)
        print ("Temperature (F) = ",temp_f)
        return temp_c, temp_f

def animation():
    def animate(i):

        pullData = open("Tempdata.txt","r").read()
        dataArray = pullData.split('\n')
        time = []
        temp = []
        for eachLine in dataArray:
            if len(eachLine)>1:
                x,y = eachLine.split(',')
                time.append(parser.parse(x))
                temp.append(int(float(y)))
        ax1.clear()
        ax1.plot(time,temp)
        plt.title("Temperature changes over Time")
        plt.xlabel("Date/Time (HH:MM)")
        plt.ylabel("Temperature (\u2103)")
        fig.autofmt_xdate()

        ani = animation.FuncAnimation(fig, animate, interval=1000)
        plt.show()
        plt.draw()
        plt.pause(0.0001)
        return ani


while True:    
    print(read_temp())
    print ("--------------------------------------")
    animation()
    time.sleep(2)

来源:https://stackoverflow.com/questions/42450656/display-graph-of-data-from-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!