Raspberry Piに温湿度センサーを取り付けてデータを取得できるようにしたので、 メモを残します。
前提
実際には既存環境で動作済みの環境を、 別のRaspberry Piへ移設した際の記録です。 そのため完全イチからのセットアップを行う際には足りない情報があるかもしれません。
環境
- 本体: Raspberry Pi 3 Model B
- センサー: DHT22モジュール
参考URL
構築
※既存の環境に構築を行ったため、環境の準備は省きます。
- DHT22をRaspberry Pi本体に接続する
ターミナルから”pinout”コマンドを実行。 接続箇所を確認し、それぞれ接続を行います。
Raspberry Pi側 | DHT22側 |
---|---|
5V | VCC |
GND | GND |
GPIO 22 | DATA |


-
必要なパッケージをインストールする
# libgpiod2 をインストールする sudo apt-get install libgpiod2
-
Pythonの仮想環境を作り、必要なパッケージをインストールする
# 任意のディレクトリに移動後、以下を実行 # Pythonの仮想環境を作成 python -m venv .venv # 作成した仮想環境を有効化する . .venv/bin/activate # adafruit-circuitpython-dht をインストールする pip install adafruit-circuitpython-dht
-
温度・湿度の計測を行う
Adafruit_CircuitPython_DHTのGitHubページに記載のサンプルコードを実行してみます。
以下サンプルコード ※実行前に★部分を変更してください。
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time
import board
import adafruit_dht
#Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT22(board.D18) ★D18の部分を、実際に接続したGPIO(今回は22)の数字に変更してください。
#you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
#This may be necessary on a Linux single board computer like the Raspberry Pi,
#but it will not work in CircuitPython.
#dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False)
while True:
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print(f"Temp: {temperature_f:.1f} F / {temperature_c:.1f} C Humidity: {humidity}% ")
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(2.0)
以下は実行結果です。
(.venv) hoge@fuga:~/scripts/dht22 $ python3 sample.py
Temp: 83.3 F / 28.5 C Humidity: 49.8%
Temp: 83.3 F / 28.5 C Humidity: 49.8%
A full buffer was not returned. Try again.
Temp: 83.3 F / 28.5 C Humidity: 49.8%
Checksum did not validate. Try again.
Temp: 83.3 F / 28.5 C Humidity: 49.9%
Temp: 83.1 F / 28.4 C Humidity: 49.8%
Temp: 83.1 F / 28.4 C Humidity: 49.9%
A full buffer was not returned. Try again.
Temp: 83.1 F / 28.4 C Humidity: 49.9%
時々エラーになりますが、それっぽい数字の取得ができました。 息を吹きかけると温度湿度ともに上昇するので、きちんと計測できていそうです。
コメント