-
毎日試しては更新するように心がけます
この記事について
今回はRaspberryPのスターターキットを購入したので色々と遊んでみる
OSOYOO(オソヨー) Raspberry Pi... https://www.amazon.jp/dp/B01M6ZFNSS?ref=ppx_pop_mob_ap_share
今回は温湿度センサー
温度と湿度を計測してプログラム上に出力する。
ライブラリもありプログラムを組むのも簡単だった。
環境
Raspbian GNU / Linux 9.8(stretch)
Python 3.7.4
用意するもの
RaspberryPi Model B+
ACアダプター(5V/3A)
温湿度センサー(DHT11 Temperature & Humidity sensor Module)
ジャンパワイヤ 3本
センサー
DHT11は温度と湿度両方を計測できるセンサー。
計測範囲 | ||
---|---|---|
湿度 | 20% RH | 90% |
温度 | 0℃ | 50℃ |
RH
ある温度の空気中に含みうる最大限の水分量(飽和水蒸気量)に比べてどの程度の水分を含んでいるか。一般的に湿度を表す時に使用。
Adafruit Python DHT
RaspberryPiで温度湿度の数値を読み取るためのライブラリ。
これをインストールして簡単にプログラムが組める。
インストール
Python3でインストールする
依存関係
sudo apt-get update
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
pip
sudo pip3 install Adafruit_DHT
コードを書く
import Adafruit_DHT as DHT
import datetime
import time
sensor = DHT.DHT11
pin = 14
for _ in range(10):
while True:
humidity, temperature = DHT.read_retry(sensor, pin)
if (90 < humidity < 20) or (50 < temperature < 0):
print('Error', humidity, temperature)
time.sleep(0.1)
continue
break
date = datetime.datetime.now()
print('湿度 => ' + str(humidity), '温度 => ' + str(temperature))
print(date.strftime('%Y/%m/%d %H:%M:%S'))
time.sleep(10)
read_retry(sensor, pin)
この関数はセンサーの値を取得するまで15回読み取りを試行する
再試行の間に2秒待機
値が取得できたら
humidity
変数とtemperature
変数に入れる
if (90 < humidity < 20) or (50 < temperature < 0)
計測範囲をもとに湿度は20%以下90%以上、温度は50度以上0度以下なら文字列'ERROR'と各センサー値を表示する。
date = datetime.datetime.now()
print('湿度 => ' + str(humidity), '温度 => ' + str(temperature))
print(date.strftime('%Y/%m/%d %H:%M:%S'))
time.sleep(10)
センサーからの値を出力して10秒待機してループに戻る。
合計10回計測する。
繋いでみる
調べていたら4本足のDHT11もあったがこれは抵抗型湿度測定が含まれている。
ピン | ポート | |
---|---|---|
2番 | 5V | VCC |
6番 | GND | GND |
8番 | 14 | DATA |
実行する
湿度 => 70.0 温度 => 24.0
2019/08/23 19:52:28
湿度 => 69.0 温度 => 24.0
2019/08/23 19:52:41
湿度 => 69.0 温度 => 25.0
2019/08/23 19:52:52
湿度 => 69.0 温度 => 25.0
2019/08/23 19:53:03
湿度 => 162.0 温度 => 12.0
2019/08/23 19:53:16
湿度 => 68.0 温度 => 25.0
2019/08/23 19:53:26
湿度 => 68.0 温度 => 24.0
2019/08/23 19:53:42
湿度 => 68.0 温度 => 24.0
2019/08/23 19:53:55
湿度 => 68.0 温度 => 25.0
2019/08/23 19:54:08
湿度 => 68.0 温度 => 25.0
2019/08/23 19:54:19
上手く動いた。
まとめ
- ライブラリがあったから簡単に動かせた。
- 正確かどうかはわからないがDHT22はDHT11より正確らしい。