NRF52840とコンピュータ間のBluetooth通信

必要

nrf52840をメインコントロールとして各種センサーを接続し、センサーデータをBluetooth経由でコンピュータに送信し受信します。プロトコルスタックが異なるため、hc-06 は nrf52840 を取得できません。

実際の構成

  1. メインコントロールはSeeed XIAO BLEで、そのチップは Arduino ベースを搭載した nrf52840 であるため、ユーザーの上位層は Arduino IDE を使用してコードをプログラミングします。
  • 彼の Bluetooth 部分は Adafruit 関連のライブラリを使用しています。
  1. PC 部分は Adafruit_CircuitPython_BLE ライブラリを練習で使用するため、Linux で動作しますが、当面は Windows では動作しません。
  • OS:Ubuntu 20.04

実装プロセス

ライブラリをインストールする

私のPythonのバージョンは3.8で、ubuntuに付属しています

pip3 install adafruit-circuitpython-ble

仮想環境にインストールする必要がある場合は、

mkdir project-name && cd project-name
python3 -m venv .venv
source .venv/bin/activate
pip3 install adafruit-circuitpython-ble

テスト

from adafruit_ble import BLERadio

radio = BLERadio()
print("scanning")
found = set()
for entry in radio.start_scan(timeout=60, minimum_rssi=-80):
    addr = entry.address
    if addr not in found:
        print(entry)
    found.add(addr)

print("scan done")

公式ライブラリ: Adafruit_CircuitPython_BLE

Bluetoothを検索して接続する

上記のデモは Bluetooth を取得する部分ですが、テストを通じて nrf52840 の Bluetooth を簡単に取得することができます。次に、接続を行います。

radio.connect(entry)

見つけたら探すのをやめる

radio.stop_scan()

データ送信

ntypes は送信データの数で、デフォルトでは最大 64 です。ダウンロードしたデータ パッケージの UARTService クラスでそのバッファ容量を変更できます。
データの読み取りに使用できる関数は 3 つあります。

def read(self, nbytes: Optional[int] = None) -> Optional[bytes]
def readinto(self, buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]
def readline(self) -> Optional[bytes]

データを書き込むと、次のことが可能になります。

def write(self, buf: ReadableBuffer) -> None

例えば

data = device[UARTService].read(ntypes)
message = data.decode()

特定のケースについては、私の githubコードを参照してください。

おすすめ

転載: blog.csdn.net/Carol_learning/article/details/128754779