LoginSignup
31
31

More than 5 years have passed since last update.

RaspberryPizeroでbluetoothシリアル通信をする方法

Posted at

RaspberryPiとAndroidスマホをBluetoothで通信させたい

  • RaspberryPizeroがある
  • 小さいからスマホと無線で連携させたい
  • wifiはアクセスポイントが必要&スマホはインターネットにつなぎたい

RaspberryPizeroの紹介

  • 小型パソコンと言われるRaspberryPiのさらに小型版
  • 小さいけどLinuxが動作可能
  • バージョンが上がってRaspberryPi用のカメラを接続できるようになった(要zero用カメラケーブル)

Bluetoothでシリアル通信

  • Bluetoothの通信方法の一つ(詳しい説明は割愛)
  • Androidのサンプルアプリの一部を修正するだけで通信できる(簡単)

作ったもの,作り方

RaspberryPizero編

  • 初期設定はRaspberryPizeroの設定が必要なため,直接かssh接続できるようにしとく
  • BluetoothのUSBドングルが必要
  • OSはRaspbian
  • Bluetoothライブラリの導入
sudo apt-get install bluez
sudo apt-get install bluetooth blueman bluez-tool
  • Bluetoothのペアリング

    • ペアリングするデバイス(今回はAndroid)を検索可能状態にしておく
    sudo bluetoothctl -a
    scan on //ペアリング対象のアドレスを確認
    scan off
    pair <ペアリング対象のアドレス>
    trust <ペアリング対象のアドレス> //次回起動時に自動接続
    
  • BluetoothのSPP(シリアル通信)設定

    • /etc/systemd/system/dbus-org.bluez.serviceに以下の記述を追加(設定後再起動した方が良い)
    ExecStart=/usr/lib/bluetooth/bluetotthd -C
    ExecStartPost=/usr/bin/sdptool add SP
    
  • Bluetoothのシリアル接続をC言語から利用する

    • ライブラリ導入
    sudo apt-get install libbluetooth-dev
    
    gcc <.cファイル> -o <出力ファイル> -lbluetooth
    
    • 出力されたファイルを実行することでBluetoothサーバーとしてペアリングしたデバイスからの接続を待つ状態になる

Androidアプリ編

  • AndroidStudioを利用
  • 起動時にImport an Android code sampleからBluetooth Chatを選択してプロジェクトを作成
  • コードの修正

    • サンプルプロジェクトをBlueotthのシリアル通信に対応させます
    • BluetoothChatService.javaの50,51行目を以下のように変更(シリアル通信用にUUIDを変更)
    private static final UUID MY_UUID_SECURE =
                UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
    • デバッグなどでRaspberryPizeroとペアリングしたAndroidデバイスにインストール

接続

  • RaspberryPizeroで作成したrfcomm-serverプログラムを起動
  • AndroidにインストールしたBluetotth Chatアプリを起動
  • AndroidアプリのConnect a device - secureまたはBluetoothのマークからペアリングしたRaspberryPizeroを選択
  • テキストボックスに文字を入力してsendを押す
  • 入力文字と同じ文字が帰ってきたらシリアル通信成功!

Screenshot_2016-10-09-17-50-02.png

今後の課題

  • 初期のペアリング設定にsshか直接入力が必要なためもっと簡単にペアリングしたい
  • 複数デバイスからの接続や別のBluetoothプロトコル通信と併用して何か作りたい
31
31
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31