LoginSignup
5
4

ESP32-S3でBLE-Keyboardを使うとき

Posted at

はじめに

Arduino環境でESP32-S3をBLE-Keyboardにして使うとき、ちょっとした罠にはハマったので、メモしておく。

1. Arduino IDE

ボードマネージャに以下のURLを追加しESP32-S3ボードを追加する。出典

https://espressif.github.io/arduino-esp32/package_esp32_index.json
+ ↓こちらのURLでダウンロードされるjsonと内容は同じ
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

- ↓こちらのURLには、ESP32-S3が無い
https://dl.espressif.com/dl/package_esp32_index.json

2. ライブラリを追加

  1. ESP32-BLE-Keyboard <主役>
  2. NimBLE-Arduino

2.1 ESP32-BLE-Keyboardライブラリの追加

  • 上のReleaseからESP32-BLE-Keyboard.zipをダウンロード
  • Arduino IDEの「ZIP形式のライブラリをインストール」でダウンロードしたzipファイルを指定してインストールする

2.2 NimBLE-Arduinoライブラリの追加

ESP32-S3でESP32-BLE-Keyboardライブラリを使う場合は、NimBLE-Arduinoライブラリが必要とのこと(USE_NIMBLE)。出典

  • Arduino IDEの「ライブラリを管理」にてNimBLE-Arduinoを検索しインストールする

3. USE_NIMBLE

#define USE_NIMBLEをソースコードの先頭に追加する。

#define USE_NIMBLE
#include <BleKeyboard.h>

4. USB-Keyboardと共存させる場合

USBにつながっている時は、USBキーボードとして動作し、USBにつながっていない時は、BLEキーボードとして動作させたい場合は、さらに以下の対応が必要。

4.1 KeyReportが重複

USBとBLEでKeyReportが重複してコンパイルエラーとなる場合は、BLE側の以下のソースを手修正する。

BleKeyboard.h
- } KeyReport;
+ } BLEKeyReport;

- KeyReport          _keyReport;
+ BLEKeyReport       _keyReport;

-  void sendReport(KeyReport* keys);
+  void sendReport(BLEKeyReport* keys);
BleKeyboard.cpp
- void BleKeyboard::sendReport(KeyReport* keys)
+ void BleKeyboard::sendReport(BLEKeyReport* keys)

-  this->inputKeyboard->setValue((uint8_t*)keys, sizeof(KeyReport));
+  this->inputKeyboard->setValue((uint8_t*)keys, sizeof(BLEKeyReport));

↓このプルリクがマスタに反映されれば不要な対応。

4.2 #define HID_SUBCLASS_NONE (0)がエラーとなる

NimBLE-Arduino/src/HIDTypes.h:29:29: error: expected identifier before '(' token
 #define HID_SUBCLASS_NONE   (0)
                             ^
arduino_tinyusb/tinyusb/src/class/hid/hid.h:63:3: note: in expansion of macro 'HID_SUBCLASS_NONE'
   HID_SUBCLASS_NONE = 0, ///< No Subclass

NimBLE-ArduinoHIDTypes.hと、arduino_tinyusb/tinyusb/src/class/hid/hid.hHID_SUBCLASS_NONEの定義が重複する(enumの名前が#defineに置き換るエラー)。
値は同じであるため、NimBLE-Arduinoの方をコメントアウトする。

HIDTypes.h
-    #define HID_SUBCLASS_NONE   (0)
+ // #define HID_SUBCLASS_NONE   (0)

5. ペアリングした後

スマホに初めてペアリングしたとき下記のエラーが出るが、キーボードの送信は正く出来ているのでそのまま使える。また、スマホ側にはエラーは見えない。

BT_GATT: GATT_INSUF_AUTHENTICATION
         or
BT_GATT: GATT_INSUF_ENCRYPTION

おわりに

以上で、コンパイル&アップロード&上手く動作するはずだ。

5
4
0

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
5
4