0

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)
Community
  • 1
  • 1
shuynh84
  • 59
  • 8
  • It sounds like you are trying to update your plot live as you collect your temperature data. Probably what is happening here is that the script is waiting on `plt.show()` to complete before continuing with the `while` loop. When you close the figure, your loop should continue to run. For a solution to your question see similar questions [here](http://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib) and [here](http://stackoverflow.com/questions/10944621/dynamically-updating-plot-in-matplotlib). – Brian Feb 25 '17 at 04:55
  • 1
    Possible duplicate of [real-time plotting in while loop with matplotlib](http://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib) – Brian Feb 25 '17 at 04:55
  • Thanks @Brian for the quick reply! I removed the last line `time.sleep(2)` and add `plt.pause(0.0001)` but it still getting hung up on the `plt.show()` – shuynh84 Feb 25 '17 at 22:07
  • That's because you shouldn't be using `plt.show()` in this use case. Please see the links in my comments, above, for alternative solutions. – Brian Feb 25 '17 at 22:13
  • I'm very new to python is there anyway you can show me what my code would look like? thank you – shuynh84 Feb 25 '17 at 23:45

0 Answers0