ラズベリーパイPico Wを介してブルートゥースでDCモータを制御してみようでラズベリーパイPico Wを子機(ペリフェラル)にして、パソコンを親機(セントラル)にして、子機側につないだDCモータを制御してみました。
今回は親機もラズベリーパイPico Wにしてみます。
ラズベリーパイPico W同士をBluetooth接続してLチカをしてみるでラズベリーパイPico Wを親機にして、子機に対して何らかの値を送信したことを前提にして話を進めます。
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():
try:
central.write("f\r\n", with_response)
time.sleep(2)
central.write("r\r\n", with_response)
time.sleep(2)
central.write("s\r\n", with_response)
except:
print("TX failed")
break
print("Disconnected")
※0x000c や b'f\r\n' 等の値の説明は省略します。
このコードを実行してみると、子機(ペリフェラル)のラズベリーパイPico Wの方で
のように動作になります。