今天會延續昨天做的事,然後嘗試使用感測機接收資料並且修改一下程式碼儲存至csv檔,以便進行後續的視覺化。
首先修改昨天的程式碼
import Adafruit_DHT
import time
import csv
sensor = Adafruit_DHT.DHT22
sensor_pin = 4
running = True
csvfile = "sensor_readings_1.csv"
while running:
try:
#read the humidity and temperature
humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin)
if humidity is not None and temperature is not None:
humidity = round(humidity, 2)
temperature = round(temperature, 2)
print ('Temperature = {0:0.1f}*C Humidity = {1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
timeC = time.strftime("%I")+':' +time.strftime("%M")+':'+time.strftime("%S")
data = [temperature, timeC]
with open(csvfile, "a") as output:
writer = csv.writer(output, delimiter=",", lineterminator ='\n')
writer.writerow(data)
time.sleep(1)
except KeyboardInterrupt:
print ('Program stopped')
記得time.sleep可以自行設定更長的間隔,因為現在是實驗所以設為1秒。
接下來我們已經產出了csv檔,所以現在可以使用各種視覺化工具來畫圖,我們來用一個很常見的python matplotlib畫折線圖。
首先先安裝matplotlib
sudo apt-get install python3-matplotlib
再來編緝我們的程式碼
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.animation as animation
from datetime import datetime
fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#fff8dc')
def animate(i):
ftemp = 'sensor_readings_1.csv'
fh = open(ftemp)
temp = list()
timeC = list()
for line in fh:
pieces = line.split(',')
degree = pieces[0]
timeB = pieces[1]
ax = fig.add_subplot(1,1,1,facecolor='white')
ax.plot(timeB, degree, 'o-', linewidth = 3.3)
plt.ylabel('Temperature')
plt.xlabel('Time')
ani = animation.FuncAnimation(fig, animate, i nterval = 6000)
plt.show()
然後再執行
python3 plot.py
這樣我們就會獲得折線圖了,如果觀察時間與間隔再拉長,就可以看出更明顯的一天氣溫差異了。
您好,
請問下面三個問題
謝謝您的教學