ESP32 Arduino 上的简单模拟键盘操作

本来是以前做过的ESP32项目,但是想拿来用在别的项目上时发现找不到了。所以重新写一下这个项目,记录一下。

首先说明:使用ArduinoIDE、模块型号为esp32-wroom-32。


库文件链接:

https://github.com/T-vK/ESP32-BLE-Keyboard

期间发现了好几个库,但是这个库选择的人比较多,就是用这个库。

Arduino 也有相类似的库,介绍界面:

https://www.arduino.cc/reference/en/language/functions/usb/keyboard/

但是 Arduino 的这个 keyboard 库是基于 USB 端口的,都用了 ESP32 了,高低不得整一个蓝牙?


BleKeyboard 介绍

BleKeyboard 的函数接口和 Keyboard 库几乎相同,所以用起来也很方便,可直接参考 Keyboard 库的一些函数介绍。

Keyboard 的函数:


库文件介绍

构造函数

找到了库文件,先看看类的构造函数:

//函数定义
BleKeyboard::BleKeyboard(std::string deviceName, std::string deviceManufacturer, uint8_t batteryLevel)

//class 中的声明以及默认参数
BleKeyboard(std::string deviceName = "ESP32 Keyboard", std::string deviceManufacturer = "Espressif", uint8_t batteryLevel = 100);

解释一下这部分函数:

第一个参数为设备名称,第二个参数为设备制造商名称,第三个参数为电池点亮。

本库的构造函数没有使用函数重载,创建类对象时如果不提供参数将会使用默认参数。

BleKeyboard提供的公共接口函数


函数示例

#include <BleKeyboard.h>
BleKeyboard blekeyboard("ESP32kEYBOARD","Espressif",50);    
                        // 设备名,制造商,电量
const int OutPIN = 0;    // 定义按键端口

void setup() 
{
  Serial.begin(115200);
  blekeyboard.begin();    
  Serial.println("蓝牙键盘准备就绪");
}

void loop() 
{
  if(blekeyboard.isConnected())    // 判断连接是否成功
  {
    static int a = 1;    // 第一次连接上打印连接成功
    if(a == 1)
    {
      Serial.println("蓝牙已连接");
      a++;
    }

    if(!digitalRead(OutPIN))    // 按键被按下
    {
      delay(50);
      if(!digitalRead(OutPIN))    // 消抖,也不知道ESP32上用不用消抖
      {
        Serial.println("输出");    
        
        blekeyboard.println("Don't say anything that is not conducive to unity");    // 打印字符
        delay(100);
        blekeyboard.write(KEY_NUM_ENTER);    // 按键按下enter
      }
    }
  }
  else    // 没有连接成功
  {
    Serial.println("蓝牙未连接");    // 循环打印蓝牙未连接
    delay(1000);
  }
}

实现按键按下后,输入字符串+Enter。

这有一点问题,通过 blekeyboard.println 打印中文字符时,会出现乱码输出的问题。不知道是不是与编码格式有关。

还有一个问题

class BleKeyboard : public Print, public BLEServerCallbacks, public BLECharacteristicCallbacks

这个类构造函数后面的这些不懂。他是怎么继承的?


OK,算是暂时的能用这个库了!能用在其他项目上了!!

物联沃分享整理
物联沃-IOTWORD物联网 » ESP32 Arduino 上的简单模拟键盘操作

发表评论