esp32 模拟蓝牙键盘不生效一例

esp32 使用 GitHub - T-vK/ESP32-BLE-Keyboard: Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)

这个开源库模拟键盘功能早之前已经玩过,生效,昨天再来玩的时候发觉莫名奇妙居然又不能用了,各种折腾:换了3种单片机,c3 s3, woom,找各种框架,花了将近一天。

最后尝试了官方的另外一种方案最终生效:

就是 platformio下加上这样的配置:

lib_deps = 
  NimBLE-Arduino

build_flags = 
  -D USE_NIMBLE

所谓的轻量级蓝牙协议栈.

没有搞懂的就是为啥默认的配置,默认的代码以前可以用现在为啥不能用了;其二,一直以为蓝牙是轻量级的东西,结果运行起来发觉发热量在s3上还是很大的,而且持续电流有100多ma.

### 使用ESP32模拟蓝牙键盘和鼠标的实现方法 为了使ESP32能够作为蓝牙键盘或鼠标运行,需依赖于其内置的BLE(Bluetooth Low Energy)模块以及特定库的支持。具体来说,`ESP32-BLE-Keyboard` 和 `ESP32-BLE-Mouse` 这两个Arduino库提供了必要的接口来配置ESP32设备以模仿这些输入装置的行为。 #### 准备工作环境 确保已安装PlatformIO IDE插件至VSCode环境中,并完成ESP32开发板的相关设置[^3]。接着,在项目的`platformio.ini`文件内指定所需的框架版本和其他参数: ```ini [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino lib_deps = blehidemulator ``` #### 安装必要库 除了上述提到的基础配置之外,还需要额外引入`blehidemulator`库用于支持BLE HID协议栈的操作。这一步骤同样可以在`platformio.ini`中定义,如上面所示。 #### 编写代码示例 下面给出一段简单的C++程序片段,展示了如何初始化并控制ESP32作为一个虚拟蓝牙键盘发送按键事件给配对成功的主机端;对于鼠标的仿真逻辑与此相似,只需调整相应的API调用即可。 ##### 蓝牙键盘实例代码 ```cpp #include "BLEDevice.h" #include "BLEUtils.h" #include "BLEScan.h" #include "BLEAdvertisedDevice.h" // 导入 BLE 键盘类库 #include <BLEKeyboard.h> void setup() { Serial.begin(115200); // 初始化 BLE 设备 BLEDevice::init("MyESP32Keyboard"); // 创建 BLE 键盘对象 p BleKeyboard = new BLEKeyboard(); // 开始广播等待连接... while (!pBleKeyboard->begin()) { delay(1000); Serial.println("Failed to init keyboard, retrying!"); } } void loop() { static unsigned long lastTime = millis(); if (millis() - lastTime >= 5000) { // 每隔五秒触发一次按键动作 pBleKeyboard->write('A'); // 发送大写字母 A delay(100); pBleKeyboard->keyReleaseAll(); // 释放所有按下的键位 lastTime = millis(); } } ``` ##### 蓝牙鼠标实例代码 ```cpp #include "BLEDevice.h" #include "BLEUtils.h" #include "BLEScan.h" #include "BLEAdvertisedDevice.h" // 导入 BLE 鼠标类库 #include <BLEMIDI.h> #include <BLERobotControl.h> #include <BLEMouse.h> void setup() { Serial.begin(115200); // 初始化 BLE 设备 BLEDevice::init("MyESP32Mouse"); // 创建 BLE 鼠标对象 pBleMouse = new BLEMouse(); // 同样地启动服务准备接受客户端请求建立链接 while(!pBleMouse->begin()){ delay(1000); Serial.println("Failed to init mouse, retrying!"); } } void loop(){ static unsigned long prevMillis = 0; if(millis()-prevMillis>2000){ // 每两秒钟移动指针位置 int moveX=random(-10,+10),moveY=random(-10,+10); pBleMouse->move(moveX , moveY ); prevMillis=millis(); } } ``` 以上就是关于ESP32模拟蓝牙键盘与鼠标的简易指南及其对应的源码示范[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值