我是Python的新手。我正在使用温度传感器将写入数据读取到txt文件。当我运行此代码时,它会将温度写入一次,绘制图形并停止工作直到我关闭图形。
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)
我编辑了代码及其日志数据,但不再显示图表。我正在使用SunFounder DS18B20 Temp传感器并修改代码,以便将数据记录到本地txt文件中,并使用txt文件中的数据对其进行绘图。
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)