为了开发一个 ardunio 的蓝牙选歌器,网络上普遍推荐使用:
https://github.com/T-vK/ESP32-BLE-Keyboard
结果搞了好几天,就是不行。最后发现,下面两点非常重要:
- 使用 NimBle-ardunio 库
- 这个库目前是2.1.2 ,一定要使用老的版本,我使用1.4.0 好了。
分享给有缘人。
代码
#include <BleKeyboard.h>
BleKeyboard bleKeyboard;
bool deviceConnected = false; // 标记设备连接状态void setup() {Serial.begin(115200);Serial.println("start ble keyboard...");bleKeyboard.begin();Serial.println("start ble keyboard finish");
}void loop() {Serial.println("Loop work");// 检查设备连接状态if (bleKeyboard.isConnected()) {Serial.println("bleKeyboard.isConnected()");if (!deviceConnected) {Serial.println("device is connected");deviceConnected = true;}// 检查串口输入命令if (Serial.available()) {char command = Serial.read();// 打印接收到的命令Serial.print("Received command: ");Serial.println(command);// 通过串口输入字母进行 触发if (command == 'n') {Serial.println("send next command");bleKeyboard.write(KEY_MEDIA_NEXT_TRACK); // 发送“下一首”命令} else if (command == 'p') {Serial.println("send previous command");bleKeyboard.write(KEY_MEDIA_PREVIOUS_TRACK); // 发送“上一首”命令} else if (command == 's') {Serial.println("send start command");bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE); // 发送“上一首”命令}else if (command == 'o') {Serial.println("send stop command");bleKeyboard.write(KEY_MEDIA_STOP); // 发送“关闭”命令}else if (command == 'u') {Serial.println("send up command");bleKeyboard.write(KEY_UP_ARROW); // 发送“向上”命令}else if (command == 'd') {Serial.println("send down command");bleKeyboard.write(KEY_DOWN_ARROW); // 发送“向下”命令}else {Serial.println("Unknown command");//可以补充// KEY_LEFT_CTRL// KEY_LEFT_SHIFT// KEY_LEFT_ALT// KEY_LEFT_GUI// KEY_RIGHT_CTRL// KEY_RIGHT_SHIFT// KEY_RIGHT_ALT// KEY_RIGHT_GUI// KEY_UP_ARROW// KEY_DOWN_ARROW// KEY_LEFT_ARROW// KEY_RIGHT_ARROW// KEY_BACKSPACE// KEY_TAB// KEY_RETURN// KEY_ESC// KEY_INSERT// KEY_PRTSC// KEY_DELETE// KEY_PAGE_UP// KEY_PAGE_DOWN// KEY_HOME// KEY_END// KEY_CAPS_LOCK// KEY_F1// KEY_F2// KEY_F3// KEY_F4// KEY_F5// KEY_F6// KEY_F7// KEY_F8// KEY_F9// KEY_F10// KEY_F11// KEY_F12// KEY_F13// KEY_F14// KEY_F15// KEY_F16// KEY_F17// KEY_F18// KEY_F19// KEY_F20// KEY_F21// KEY_F22// KEY_F23// KEY_F24// KEY_NUM_0// KEY_NUM_1// KEY_NUM_2// KEY_NUM_3// KEY_NUM_4// KEY_NUM_5// KEY_NUM_6// KEY_NUM_7// KEY_NUM_8// KEY_NUM_9// KEY_NUM_SLASH// KEY_NUM_ASTERISK// KEY_NUM_MINUS// KEY_NUM_PLUS// KEY_NUM_ENTER// KEY_NUM_PERIOD}}} else {Serial.println("bleKeyboard.disConnected()");// 当设备断开连接时重新初始化蓝牙if (deviceConnected) {Serial.println("device disconnected, restarting Bluetooth broadcast");deviceConnected = false;}//bleKeyboard.begin(); // 重新开始广播以允许重新连接}delay(2000); // 控制发送频率,避免误操作
}