LoginSignup
0
0

More than 1 year has passed since last update.

Raspberry Pi 4 で 温湿度気圧センサー(BME280)の測定結果を出力する

Posted at

RaspberryPi4に温湿度気圧センサーのBME280を接続、測定結果を出力した。

はじめに

サンプルコードはSWITCH SCIENCEのサンプルプログラム(bme280_sample.py)を使う。
GitHubはこちら

wgetで取得

$ wget https://raw.githubusercontent.com/SWITCHSCIENCE/BME280/master/Python27/bme280_sample.py

準備

配線
Raspberry Pi 4との配線は配線図の通りに実施。
具体的には、以下の通り。

SDI      (BME280)  -> GPIO2 P03 (Raspberry Pi SDA1)
SCK      (BME280)  -> GPIO3 P05 (Raspberry Pi SCL1)
GND,SDO  (BME280)  -> GND  P09 (Raspberry Pi)
Vio,CSB  (BME280)  -> 3.3v P01 (Raspberry Pi)

以下のコマンドで 0x76 が接続アドレスであることがわかる。

$ sudo i2cdetect -y 1

0x76じゃない場合はサンプルコード修正必要あり

モジュールインストール

$ sudo apt-get update
$ sudo apt install -y python-smbus
$ sudo pip install smbus2

Raspberry Pi から I2CをPythonで制御するため、smbus2をインストール。
私はこのとき、赤外線アレイセンサ(AMG8833)を使った後だったため、smbus2が無いと以下のエラーになった。

File "/home/hogehoge/bme280_sample.py", line 3, in <module>
    from smbus2 import SMBus
ModuleNotFoundError: No module named 'smbus2'

サンプルコード修正

サンプルコードはPython2.7で作られており、Python3で実行すると以下のエラーになる。

  File "/home/hogehoge/bme280_sample.py", line 95
    print "pressure : %7.2f hPa" % (pressure/100)
          ^
SyntaxError: invalid syntax

Python3で実行するため、以下のように修正する。
修正箇所は、95行目、103行目、117行目。

修正前) print "pressure : %7.2f hPa" % (pressure/100)
修正後) print ("pressure : {:7.2f} hPa".format(pressure/100))

実行

$ sudo python3 bme280_sample.py 
temp :  24.04 ℃
pressure : 1007.90 hPa
hum :  50.68 %
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