LoginSignup
0
0

More than 1 year has passed since last update.

Adafruit_DHTがError accessing GPIOで失敗する場合の対処

Posted at

RaspberryPiでAdafruit_DHTを利用して温湿度センサを動かそうとした際に以下のエラーで失敗した
エラーでググったが解決策にたどり着くまで時間がかかったので書き残しておく

RuntimeError: Error accessing GPIO. Make sure program is run as root with sudo!

結論

Adafruitのフォーラムにあった
https://forums.adafruit.com/viewtopic.php?f=24&t=168118
この通りやれば解決した
https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/python-setup

経緯

これまでRaspberryPi 4B(64bit)で温湿度センサAM2302(DHT22)を制御していたが、画像撮影するraspistillが64bitのRaspberry Pi OSでは使えないことに気づき、32bitでOSを再インストールして再び同じように温湿度センサの環境をこことか見ながら構築していた際に上記エラーが出た
俺はなにも悪いことをしていない

対処方法

エラーに書いてる通りGPIOピンの状況確認やsudo付けて実行など一通りやってダメだったのでググったが同様の報告があまりなく、最終的にはAdafruitのフォーラムにて案内されていたやり方にて対処した
https://forums.adafruit.com/viewtopic.php?f=24&t=168118

フォーラムによると

Our Adafruit_DHT library is deprecated. We are now using the CircuitPython_DHT Library which will correctly identify your board as Pi4 based (BCM2835) instead of confusing it for a BeagleBone Black as the error indicates.

Adafruit_DHTは非推奨で今はCircuitPython_DHTとかいうのがあるよ、らしい

な、なにー!!! 今まで俺が使っていたAdafruit_DHTは…!?

なんでこのエラーが出たのかは最後まで分からなかったので知ってたら教えてください

CircuitPython_DHTインストール

言われた通りにadafruit-circuitpython-dhtlibgpiod2をインストール

pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2

温度・湿度取得コード

https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/python-setup
CircuitPython_DHT用のサンプルコードがあったので自分用に編集

dht_simpletest.py
import time
import board
import adafruit_dht

def get_temp_humidity():
    dhtDevice = adafruit_dht.DHT22(board.D20)

    try:
        temperature_c = dhtDevice.temperature
        humidity = dhtDevice.humidity
        print('{:.1f},{}'.format(temperature_c, humidity))

    except RuntimeError as error:
        print(error.args[0])

    except Exception as error:
        dhtDevice.exit()

例外処理はテキトーなので適宜変更してほしい
これでとりあえずpython3 dht_simpletest.pyで温度湿度が26.8,58.9のような感じで出力できるようになった

これまでAdafruit_DHTがpython2でしか動かなかったので地味にうれしい

おわり

ラズパイで熱帯魚水槽にめちゃくちゃなことをやっている
https://scrapbox.io/asyley-aqua/
#あしゅりーアクアリウム

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0