CircuitPython 10行プログラミング Step5 (9) Raspberry Pi PicoのI2C ③ 気圧センサ
I2Cバス用センサは、前回のようにライブラリがあれば、すぐに使えました。I2Cのリード/ライトを個別にプログラミングします。と思ったのですが、すでに気圧センサLPS25HBの記事がありました。
CircuitPython 10行プログラミング Step3 (7) 気圧センサLPS25HB
ここではバージョン6.2で同じように動くかを検証します。
●接続
I2Cバスにどんどんつなげていきます。
OLEDボードの端子 | SHTC3ボードの端子 | LPS25HBボードの端子 | Picoの端子(GPIO) | 名称 |
---|---|---|---|---|
GND | GND | GND | GND | GND |
Vcc | Vcc | Vcc | 3.3V | 3V3(OUT) |
SCL | SCL | SCL | GP21 | I2C0 SCL |
SDA | SDA | SDA | GP20 | I2C0 SDA |
スキャンします。
from board import *
from busio import I2C
i2c = I2C(GP21, GP20)
while not i2c.try_lock():
pass
for i in i2c.scan():
print('addr 0x{0:x}'.format(i))
i2c.deinit()
三つ見つかりました。気圧センサLPS25HBが0x5dです。
addr 0x3c
addr 0x5d
addr 0x70
●プログラム1
前回のプログラムを少し修正して関数readLPS25HB()にしました。I2Cのデータ転送速度は1MHzです。
from board import *
import busio
import adafruit_ssd1306
import time
import adafruit_shtc3
i2c = busio.I2C(GP21, GP20, frequency=1_000_000)
display = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)
sht = adafruit_shtc3.SHTC3(i2c)
def readLPS25HB():
LPS25HB_adr = 0x5d
while not i2c.try_lock():
pass
i2c.writeto(LPS25HB_adr, bytearray([0x20,0x90]))
time.sleep(0.1)
i2c.writeto(LPS25HB_adr, bytes([0x28 | 0x80]))
result = bytearray(3)
i2c.readfrom_into(LPS25HB_adr, result)
press = (result[2]<<16 | result[1]<<8 | result[0]) / 4096.0
i2c.unlock()
return press
print('start')
t0 = time.monotonic()
while 1:
display.fill(0)
display.text(str(int(time.monotonic() - t0)), 3, 3, 1)
display.text("Temperature: {:0.1f} C".format(sht.temperature),3,15,1)
display.text("Humidity: {:0.1f} %".format(sht.relative_humidity),3,27,1)
display.text("Press: {:0.0f} hPa".format(readLPS25HB()),3,40,1)
display.show()
time.sleep(3.14)
●プログラム2
プログラム1に追加して、Adafruitのライブラリの出力を同時に表示します。
ダウンロードしたlibのフォルダからadafruit_lps2x.mpyをCIRCUITPYドライブのlibフォルダにコピーします。
examplesフォルダに入っているlps2x_simpletest.pyを開き、必要な部分をプログラム1にコピーします。
from board import *
import busio
import adafruit_ssd1306
import time
import adafruit_shtc3
import adafruit_lps2x
i2c = busio.I2C(GP21, GP20, frequency=1_000_000)
display = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)
sht = adafruit_shtc3.SHTC3(i2c)
lps = adafruit_lps2x.LPS25(i2c)
def readLPS25HB():
LPS25HB_adr = 0x5d
while not i2c.try_lock():
pass
i2c.writeto(LPS25HB_adr, bytearray([0x20,0x90]))
time.sleep(0.1)
i2c.writeto(LPS25HB_adr, bytes([0x28 | 0x80]))
result = bytearray(3)
i2c.readfrom_into(LPS25HB_adr, result)
press = (result[2]<<16 | result[1]<<8 | result[0]) / 4096.0
i2c.unlock()
return press
print('start')
t0 = time.monotonic()
while 1:
display.fill(0)
display.text(str(int(time.monotonic() - t0)), 3, 3, 1)
display.text("Temperature: {:0.1f} C".format(sht.temperature),3,15,1)
display.text("Humidity: {:0.1f} %".format(sht.relative_humidity),3,27,1)
display.text("Press: {:0.0f} hPa".format(readLPS25HB()),3,40,1)
display.text("Press(lib): {:0.0f} hPa".format(lps.pressure),3,52,1)
display.show()
time.sleep(3.14)
実行中の様子です。