工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Manufacturing Technology >> 製造プロセス

Raspberry Pi 2 + Windows 10 IoT CoreでシリアルBluetooth通信を実現する

必要な部品と用品

Raspberry Pi 2 Model B ×1
汎用Bluetooth USBドングル ×1
Arduino UNO ×1
SparkFun Bluetooth Modem - BlueSMiRF Silver ×1

使用するアプリとオンラインサービス

プロジェクト概要

このプロジェクトは、Raspberry Pi 2(Windows 10 IoT Core搭載)と汎用Bluetooth USBドングルを使い、Bluetoothシリアルポートプロファイル(SPP/RFCOMM)でArduino等の組み込みデバイスとシリアル通信を行うユニバーサルWindowsアプリ(UWP)の実装例です。Microsoft公式サンプルがGATT(BLE)ベースであるのに対し、こちらはより汎用的なクラシックBluetooth SPPに特化し、古いドングルでも動作します。

背景:Bluetoothプロファイルの違い

本プロジェクトはSPPのみを扱うため、実装がシンプルです。

IoTアプリの構成

アプリは以下の機能を持ちます:

Raspberry Pi 2 + Windows 10 IoT CoreでシリアルBluetooth通信を実現する

エンドポイント(Arduino側)

Arduino Uno + Bluetoothモデム(BlueSMiRF等)で、受信した文字をそのまま返すエコースケッチを動作させます。

セットアップコード

void setup() {
  Serial.begin(115200);  // BTモデムのボーレートに合わせる
  delay(333);
  while (!Serial) ;
  delay(1000);
  Serial.println("The quick brown fox jumps over the lazy dog!");
}

ループコード

void loop() {
  char ch = Serial.read();
  while (255 == (byte)ch) { ch = Serial.read(); }
  Serial.print(ch);
}

ペアリング

Bluetoothはペアリング必須。IoT Coreはヘッドレスなので、WebポータルまたはSSH経由のコマンドラインでペアリング設定を行います。詳細は「Win 10 IoT-Core: Bluetooth Universal Windows Serial App」を参照。

プロジェクト作成手順

  1. Visual Studio 2015 で Blank App (Universal Windows) テンプレートから新規作成
  2. XAMLでUI構築:
    • テキスト要素は TextBlock、送信用のみ TextBox
    • 受信欄は TextWrapping 有効化
    • StackPanel で行ごとに横並び、さらに縦スタックで全体をレイアウト
    • デバイスリストは ListBox、ItemsSource を PairedDevices コレクションにバインド、ItemTemplate で Name プロパティを表示
  3. Package.appxmanifest の機能宣言を手動編集(XMLエディタで開く):
    <Capabilities>
      <Capability Name="internetClient" />
      <DeviceCapability Name="bluetooth.rfcomm">
        <Device Id="any">
          <Function Type="name:serialPort"/>
        </Device>
      </DeviceCapability>
    </Capabilities>
    

ペアリングデバイス情報の取得

DeviceInformationCollection DeviceInfoCollection
  = await DeviceInformation.FindAllAsync(
      RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

_pairedDevices = new ObservableCollection<PairedDeviceInfo>();
foreach (var info in DeviceInfoCollection) {
  _pairedDevices.Add(new PairedDeviceInfo {
    Name = info.Name,
    Id = info.Id,
    DeviceInfo = info
  });
}

PairedDeviceInfo クラスは Name, Id, DeviceInfo プロパティを持つ。

接続確立


_service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);
_socket = new StreamSocket();
await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);

成功すれば _socket が有効になる。try-catchでエラー処理。

受信処理(非同期ループ)


private async void Listen() {
  ReadCancellationTokenSource = new CancellationTokenSource();
  if (_socket.InputStream != null) {
    dataReaderObject = new DataReader(_socket.InputStream);
    while (true) {
      await ReadAsync(ReadCancellationTokenSource.Token);
    }
  }
}

private async Task ReadAsync(CancellationToken cancellationToken) {
  uint ReadBufferLength = 1024;
  cancellationToken.ThrowIfCancellationRequested();
  dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
  var loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
  UInt32 bytesRead = await loadAsyncTask;
  if (bytesRead > 0) {
    string recvdtxt = dataReaderObject.ReadString(bytesRead);
    // UI更新等
  }
}

送信処理(同期的)


private async void Send(string msg) {
  DataWriter dataWriteObject = new DataWriter(_socket.OutputStream);
  dataWriteObject.WriteString(msg);
  var storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
  UInt32 bytesWritten = await storeAsyncTask;
}

ボタン状態制御

接続状態に応じて送信/受信開始ボタンの有効/無効を切り替え。

ソースコードリポジトリ

製造プロセス

  1. GoPiGo v2をWindows 10 IoT Coreで拡張 - Raspberry Pi 3対応
  2. Arduino MegaでPWM制御:プッシュボタン付きLEDフェード制御チュートリアル
  3. アナログセンサー搭載・高精度圧力&気流測定デバイス
  4. Arduino NanoとMPU-6050で作るリアルタイムジャイロスコープゲーム
  5. ESP32-CAMで作る動体検知セキュリティカメラ:Discord通知対応
  6. DHT11温湿度センサーで作る温度アラート – LEDとピエゾブザーで視覚/聴覚通知
  7. Unopad: Ableton Live連携シームレスなArduino MIDIコントローラー
  8. 自作Arduino TVリモコン:電池駆動・3Dプリントケース・省電力設計
  9. ArduinoでBluetooth経由でLEDを制御 – シンプルDIYガイド
  10. Arduinoでシンプルな障害物センサーを自作 – IR LEDとフォトダイオード入門
  11. 音声で家電を操作:GoogleアシスタントとBluetoothでArduino家電制御