ラズベリーパイPico W同士をBluetooth接続してLチカをしてみる

ラズベリーパイPico WでBluetooth接続を介してLチカをしてみるでラズベリーパイPico Wを子機(ペリフェラル)にして、パソコンを親機(セントラル)にしてブルートゥース接続を行い、親機から子機にLチカの命令を送信してみました。


今回は親機の方もラズベリーパイPico Wにして、親機から子機にLチカの命令を送信してみます。

子機のコードは冒頭のリンク先の記事と同様にして、親機の方のコードを作成してみます。


ラズベリーパイPico WでBluetoothのセントラル機器を構築してみるで作成したファイルに更にファイルを追加します。


ファイル名をmain.pyとして、下記のコードを作成します。

import bluetooth
import time
from ble_simple_central import BLESimpleCentral

ble = bluetooth.BLE()
central = BLESimpleCentral(ble)

not_found = False

def on_scan(addr_type, addr, name):
    if addr_type is not None:
        print("Found peripheral:", addr_type, addr, name)
        central.connect()
    else:
        not_found = True
        print("No peripheral found.")

central.scan(callback=on_scan)

# 今回はon_rxは不要
#def on_rx(v):
    # do nothing
    
#central.on_notify(on_rx)

is_connect = True
while not central.is_connected():
    time.sleep_ms(100)
    if not_found:
        is_connect = False
        break

if is_connect:
    print("Connected")

    with_response = False

    tx = 0
    while central.is_connected():
        if tx == 0:
            tx = 1
            print("ON")
        else:
            tx = 0
            print("OFF")
        try:
            central.write(str(tx)+"\r\n", with_response)
        except:
            print("TX failed")
        time.sleep(1)

    print("Disconnected")

central.write(str(tx)+"\r\n", with_response)

の箇所で子機に対して、0 or 1の値を送信していますが、受信側ではb'1\r\n'のように改行コード付きのバイナリを要求していますので、親機でもこの仕様に合わせます。


実行してみると、子機の方でLチカが始まります。