知的好奇心 for IoT

IoT関連の知的好奇心を探求するブログです

Raspberry PiでもSHT31とBME280をBlynkで使ってOLEDにも表示してみる

Raspberry PiBlynkが使えることは知ってはいたのですが、ESP8266で用が足りていたのでずっと試してなかったんです。

ESP8266はArduinoでプログラミングするのでC++を使いますが、Raspberry Piだと普通はPythonを使うし、ネットワークへの接続とかはOS任せになるのでプログラミングはかなり楽になりそうです。しかし、センサーとかアクチュエーターのライブラリの充実度は圧倒的にArduinoに軍配が上がります。(前回の記事で紹介したCO2センサー「SENSIRION SCD30」のPythonライブラリは見つけられませんでした。)

なので、ケースバイケースでRaspberry PiとESP8266を使い分けることになると思います。

まずは、実際の写真を見てみましょう。

Raspberry Pi Zero WでSHT31とBME280をOLEDで表示させたものです。

f:id:IntellectualCuriosity:20190831210632p:plain f:id:IntellectualCuriosity:20190831220157p:plain
センサーもOLEDもI2Cインターフェースなので、接続はとっても簡単です。

f:id:IntellectualCuriosity:20190831213817p:plain f:id:IntellectualCuriosity:20190831222410p:plain

BME280はI2Cアドレスを0x77にするためにSDOと3V3を繋げる必要があります。(オレンジ線)

Raspberry Piピン配置はこのようになっています。

f:id:IntellectualCuriosity:20190831223029p:plain

上段右の3.3V、SDA、SCL、GNDを使います。

 

使用パーツ

 

事前準備

      1. raspi-configでI2Cを有効にする
        sudo raspi-configRaspberry Pi Software Configuration Toolを実行して、5 Interfacing Options - P5 I2Cを選んでI2Cを有効にします。
      2. 必要なパッケージをインストールする(Raspbian Buster Liteの場合)
        ※2019/11/30「sudo apt install libjpeg-devy」は「sudo apt install libjpeg-dev」の間違いです!
        $ sudo apt install git
        $ sudo apt install python-dev
        $ mkdir pip
        $ cd pip
        $ curl https://bootstrap.pypa.io/get-pip.py -O
        $ sudo python get-pip.py
        $ cd ..
        $ sudo apt install libjpeg-dev
        $ sudo pip install pillow
        $ sudo apt install i2c-tools
        
      3. 日本語フォントを使えるようにする(IPAフォント
        $ sudo apt install fontconfig
        $ sudo apt install fonts-ipaexfont
        
      4. Blynkライブラリのインストール
        $ git clone https://github.com/vshymanskyy/blynk-library-python.git
        $ cd blynk-library-python/
        $ sudo ./setup.py install
        $ cd ..
        
      5. Adafruit Python GPIOライブラリのインストール
        $  git clone https://github.com/adafruit/Adafruit_Python_GPIO.git
        $  cd Adafruit_Python_GPIO
        $  sudo python setup.py install
        $ cd ..
        
      6. SHT31ライブラリのインストール
        $ git clone https://github.com/ralf1070/Adafruit_Python_SHT31.git
        $ cd Adafruit_Python_SHT31
        $ sudo python setup.py install
        $ cd ..
        
      7. BME280ライブラリのインストール
        $ git clone https://github.com/adafruit/Adafruit_Python_BME280.git
        $ cd Adafruit_Python_BME280
        $ sudo python setup.py install
        $ cd ..
        
      8. SSD1306(OLED)ライブラリのインストール
        $ git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git
        $ cd Adafruit_Python_SSD1306
        $ sudo python setup.py install
        $ cd ..
        

 

SHT31用コード sht31blynk.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# SHT31 and SSD1306 program using Blynk
# September 1, 2019
# By Hiroyuki ITO
# http://intellectualcuriosity.hatenablog.com/  
# MIT Licensed.

import BlynkLib
from BlynkTimer import BlynkTimer
from Adafruit_SHT31 import *
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

BLYNK_AUTH = 'YourAuthToken'

# Initialize SHT31
sensor = SHT31(address = 0x45) # ADR pin Open 0x45 Close 0x44
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Create BlynkTimer Instance
timer = BlynkTimer()

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize SSD1306
disp.begin()
# Get display width and height.
width = disp.width
height = disp.height
# Clear display.
disp.clear()
disp.display()
# Get drawing object to draw on image.
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
#font = ImageFont.load_default()
font = ImageFont.truetype('ipaexg.ttf', 32)

# Send Sensor Data to Blynk Clound Server
def send_sensor():
    # sensor.set_heater(True)
    degrees = round(sensor.read_temperature(), 1)
    humidity = round(sensor.read_humidity(), 1)
    blynk.virtual_write(1, degrees)   # Virtual V1 pin
    blynk.virtual_write(2, humidity)  # Virtual V2 pin
    print('Temp     : {0:0.1f}℃'.format(degrees))
    print('Humidity : {0:0.1f}%'.format(humidity))
    print('')

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    draw.text((16, 0), str(degrees) + u'℃', font=font, fill=255)
    draw.text((16, 32), str(humidity) + u'%', font=font, fill=255)
    # Display image.
    disp.image(image)
    disp.display()

# Add Timers
timer.set_interval(2, send_sensor)

while True:
    blynk.run()
    timer.run()

 

BME280用コード bme280blynk.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# BME280 and SSD1306 program using Blynk
# September 1, 2019
# By Hiroyuki ITO
# http://intellectualcuriosity.hatenablog.com/  
# MIT Licensed.

import BlynkLib
from BlynkTimer import BlynkTimer
from Adafruit_BME280 import *
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

BLYNK_AUTH = 'YourAuthToken'

# Initialize BME280
sensor = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8)
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Create BlynkTimer Instance
timer = BlynkTimer()

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize SSD1306
disp.begin()
# Get display width and height.
width = disp.width
height = disp.height
# Clear display.
disp.clear()
disp.display()
# Get drawing object to draw on image.
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
#font = ImageFont.load_default()
font = ImageFont.truetype('ipaexg.ttf', 21)

# Send Sensor Data to Blynk Clound Server
def send_sensor():
    degrees = round(sensor.read_temperature(), 1)
    humidity = round(sensor.read_humidity(), 1)
    pressure = int(round(sensor.read_pressure() / 100, 0))
    blynk.virtual_write(1, degrees)   # Virtual V1 pin
    blynk.virtual_write(2, humidity)  # Virtual V2 pin
    blynk.virtual_write(3, pressure)  # Virtual V3 pin
    print('Temp      :  {0:0.1f}℃'.format(degrees))
    print('Humidity  :  {0:0.1f}%'.format(humidity))
    print('Pressure  : %dhPa' % pressure)
    print('')

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    draw.text((30, 0), str(degrees) + u'℃', font=font, fill=255)
    draw.text((30, 22), str(humidity) + '%', font=font, fill=255)
    draw.text((16, 44), str(pressure) + 'hPa', font=font, fill=255)
    # Display image.
    disp.image(image)
    disp.display()

# Add Timers
timer.set_interval(2, send_sensor)

while True:
    blynk.run()
    timer.run()

 

プログラムの実行

プログラムを実行するには、スマホでBlynkアプリの設定をしておく必要があります。

この記事を参考にしてみてください。

 スマホの作業が終わったら、以下の手順でプログラムを実行します。

      1. 適当なフォルダ(temphumなど)を作ってsht31blynk.pyかbme280blynk.pyをコピーします。
      2. プログラムのYourAuthTokenにBlynkからメールで送られてきたAuth Tokenを埋め込みます。
      3. blynk-library-pythonフォルダのBlynkTimer.pyを先ほど作ったフォルダにコピーします。
      4. sht31blynk.pyかbme280blink.pyに実行権限を与えます。

sht31blynk.pyの実行例

pi@raspberrypi:~/temphum $ ./sht31blynk.py 

    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ for Python v0.2.0 (Linux)

Temp     : 26.4℃
Humidity : 56.5%

スマホの表示例

f:id:IntellectualCuriosity:20190901011201p:plain
 

おしまい