ラズパイいじり〜温湿度ロガー編⑤
前回、計測した温湿度データをCSVに書き込みました。
今回は、計測温度によるLED点滅、点灯やコンソールへの温湿度表示を組み合わせます。
CSVファイル作成と今回を分けたことには理由があります。
LED点滅や定期的なCSVへのデータ書き込みには、Pythonにおいてはtime.sleep(t)を使って一定間隔を置いた繰り返し処理を行います。
LED点滅、CSV書き込み及びコンソールへの表示のコードを単純に並べると、1つのtime.sleep(t)に引っかかり、他が動かないようでした。
て、ことでdefで関数化して、関数①の1秒後に関数②、その1秒後に関数③、その後time.sleep(8)をつけて8秒後に関数①に戻ることにしました。
これで、10秒間隔で全体が実施されることになります。
import RPi.GPIO as GPIO
import dht11
import datetime
import sys
import time
import os
import threading
import multiprocessing
Led_pin = 25 #LED用GPIO
set_temp1 = 20 #LED点灯 set_temp2 = 10 #LED点滅 tempGpio = 18
fileName='/home/pi/TEMP_LOG/temptest_log.csv'
#initialize GPIO
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
dhtStat=dht11.DHT11(pin=tempGpio)
GPIO.setup(Led_pin, GPIO.OUT)
#stat=dhtStat.read()#温湿度情報を取得
def LED_cont():#温度状態によりLEDを点灯、点滅
stat1=dhtStat.read()#温湿度情報を取得
i = stat1.temperature
if i > set_temp1:
GPIO.output(Led_pin, GPIO.LOW)
GPIO.output(Led_pin, GPIO.HIGH)
elif i > set_temp2:
while True:
GPIO.output( Led_pin, GPIO.HIGH)
time.sleep(1)
GPIO.output( Led_pin, GPIO.LOW)
time.sleep(1)
else:
print("temperature is under",set_temp2,"C")
GPIO.output(Led_pin, GPIO.LOW)
def print_DISP():
stat2=dhtStat.read()#温湿度情報を取得
if stat2.is_valid():
print(stat2)
print("Last valid input: " + str(datetime.datetime.now()))
print("Temperature: %-3.1f C" % stat2.temperature)
print("Humidity: %-3.1f %%" % stat2.humidity)
temp = str(stat2.temperature) + "C " + str(stat2.humidity) + "%"
# time.sleep(5)
def mkcsv():#DHT11からデータを読み取りCSVに書き込み
stat3=dhtStat.read()#温湿度情報を取得
if stat3.is_valid():
now=str(datetime.datetime.now())[0:16]
data=[now,stat3.temperature,stat3.humidity]
# if stat.temperature==stat.humidity==0:
# continue
thData=open(fileName,'a')
thData.write(','.join(map(str,data))+'\n')
thData.close()
# time.sleep(10)
#ファイルがなければ作成する if not os.path.exists(fileName):
thData=open(fileName,'w')
thData.write('date_time,temp,hdmt\n')
thData.close()
try:
while True:
t1 = threading.Thread(target=mkcsv)
t2 = threading.Thread(target=LED_cont)
t3 = threading.Thread(target=print_DISP)
# time.sleep(10)
t1.start()
time.sleep(1)
t2.start()
time.sleep(1)
t3.start()
time.sleep(8)
except KeyboardInterrupt:
print("Cleanup")
GPIO.cleanup()
これでCSVに記録しつつLED操作ができました。
次回は、LCDに温湿度表示をしてみます。
この記事が気に入ったらサポートをしてみませんか?