![見出し画像](https://assets.st-note.com/production/uploads/images/75118500/rectangle_large_type_2_bac51488c2e1506b713062988474943f.jpeg?width=1200)
ラズパイいじり〜温湿度ロガー編③
前回、ラズベリーパイ に温湿度センサーDHT-11を接続して、コンソールに温湿度を表示させました。
今回は、測定した温度によりLEDを点灯、点滅させてみます。
回路は、ラズパイのGPIOピンにLEDと抵抗をつけるだけです。
![](https://assets.st-note.com/img/1648336383587-qDmEbaqs6S.jpg?width=1200)
プログラムは、温湿度センサーのサンプルプログラムをベースに、IF文で温度状況に応じたLED(GPIO25)の動作を記述します。
15度以上で点滅、20度以上で点灯です。
import RPi.GPIO as GPIO
import dht11
import datetime
import sys
import time
Led_pin = 25 #LED用GPIO
set_temp1 = 20 #LED点灯
set_temp2 = 15 #LED点滅
tempGpio = 18
#initialize GPIO
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
dhtStat=dht11.DHT11(pin=tempGpio)
GPIO.setup(Led_pin, GPIO.OUT)
#センサーDHT11からデータ取得
try:
while True:
stat=dhtStat.read()
if stat.is_valid(): #取得データをコンソールに表示、60秒インターバル
print(stat)
print("Last valid input: " + str(datetime.datetime.now()))
print("Temperature: %-3.1f C" % stat.temperature)
print("Humidity: %-3.1f %%" % stat.humidity)
temp = str(stat.temperature) + "C " + str(stat.humidity) + "%"
time.sleep(6)
i = stat.temperature
if i > set_temp1:
GPIO.output(Led_pin, GPIO.LOW)
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")
except KeyboardInterrupt:
print("Cleanup")
GPIO.cleanup()
動作テストします。16.5度で点滅です。
![](https://assets.st-note.com/production/uploads/images/75137177/picture_pc_ee4244a8886ec4a87da46e41cfc3ae70.gif)
次回は、温湿度の測定デーたをCSVファイルに記録してみます。