2019年12月9日月曜日

Raspberry PiからBluetooth経由でmicrobitの地磁気センサーの値を取得する

Raspberry PiからBluetooth経由でmicrobitの地磁気センサーの値を取得するには、以下の手順を実行します。

1. Raspberry Piにbluepyをインストール
bluepyをRaspberry Piにインストールするの手順で、bluepyをインストールします

2. micro:bitでbluetoothサービスを使用するプログラム作成
以下のような感じで一通りのbluetoothサービスを最初に追加します
また、ペアリングをしなくても利用できるようにします
※6桁キーでペアリングしたい場合は「6桁のキーでmicrobitとRaspberry PiをBluetoothペアリングする」を参照してください。

3. 地磁気センサーの値を取得するプログラム
magnetometer.py
from bluepy import btle

class MyDelegate(btle.DefaultDelegate):
  def __init__(self):
    btle.DefaultDelegate.__init__(self)

  def handleNotification(self, hd, data):
    print("notification: {}".format(data))
    x = int.from_bytes(data[0:2], byteorder='little', signed=True)
    print("X: {}".format(x))
    y = int.from_bytes(data[2:4], byteorder='little', signed=True)
    print("Y: {}".format(y))
    z = int.from_bytes(data[4:6], byteorder='little', signed=True)
    print("Z: {}".format(z))

per = btle.Peripheral("D6:89:8A:69:93:88", btle.ADDR_TYPE_RANDOM)

# Magnetometer Service
svcMag = per.getServiceByUUID("E95DF2D82-51D470AA0-62FA-1922DFA9A8")

# Magnetometer Period
#chMagPeriod = svcMag.getCharacteristics("E95D386C-251D-470A-A062-FA1922DFA9A8")[0]
#period = 80
#chMagPeriod.write(period.to_bytes(2, 'little'))

# Magnetometer data
chMagData = svcMag.getCharacteristics("E95DFB11-251D-470A-A062-FA1922DFA9A8")[0]
ch_cccd=chMagData.getDescriptors(forUUID=0x2902)[0]
ch_cccd.write(b"\x01\x00", False)

dg = MyDelegate()
per.setDelegate( dg )

print("press Ctrl+C to exit...")
while True:
  if per.waitForNotifications(0.2):
    continue

4. 地磁気センサーの値を取得するプログラムの実行
$ python3 magnetometer.py
notification: b'd\xd5\xfc~\x88Q'
X: -10908
Y: 22508
Z: 10872

〇参考情報
Bluetooth Developer Studio Level 3 Profile Report


0 件のコメント:

コメントを投稿