基于Arduino ESP32的BLE键盘实现
硬件 ESP32, 基础平台 Arduino,编程工具使用VS PlatformIO.
首先,platformio.ini
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:pico32]
platform = espressif32
board = pico32
framework = arduino
lib_extra_dirs = ~/Documents/Arduino/libraries
主函数 main.cpp
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Sketch shows how to use SimpleBLE to advertise the name of the device and change it on the press of a button
// Useful if you want to advertise some sort of message
// Button is attached between GPIO 0 and GND, and the device name changes each time the button is pressed
#include <Arduino.h>
#include <WiFi.h>
#include <BleKeyboard.h>
BleKeyboard bleKeyboard("ESP32 BLE Keyboard");
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
// Serial.setTimeout(100);
bleKeyboard.begin();
// bleKeyboard.setDelay(10);
Serial.println("Wait input you message!");
}
void loop() {
if(bleKeyboard.isConnected()) {
int n = 0;
while( Serial.available() ) {
int c = Serial.read();
bleKeyboard.write(c);
n+=1;
delay(10);
}
if( n > 0 ){
Serial.printf("Sending '%d' charactors.\r\n", n);
}
// Serial.println("Sending 'Hello world'...");
// bleKeyboard.print("Hello world");
// delay(1000);
// Serial.println("Sending Enter key...");
// bleKeyboard.write(KEY_RETURN);
// delay(1000);
// Serial.println("Sending Play/Pause media key...");
// bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);
// delay(1000);
// Serial.println("Sending Ctrl+Alt+Delete...");
// bleKeyboard.press(KEY_LEFT_CTRL);
// bleKeyboard.press(KEY_LEFT_ALT);
// bleKeyboard.press(KEY_DELETE);
// delay(100);
// bleKeyboard.releaseAll();
}
Serial.println("Waiting 0.5 seconds...");
delay(500);
}
依赖 BLEKeyboard库,来源GITHUB。
https://github.com/T-vK/ESP32-BLE-Keyboard
参考ESP32文档:
https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/api-reference/index.html
后记
Arduino的API没有找到一个完善的文档,特别是ESP32本身拥有的API,对于我这种对协议细节不太了解的,想要自己实现功能会特别困难,不知道哪位大佬能给予指点!
如果有ESP32中文文档或者组合使用API介绍,那样ESP32的发展会更好!