esp32开发一个按钮程序,当按钮按下后发送一个蓝牙按键给电脑。如何做到响应快?

9 2025-08-07 22:21

#include <Arduino.h>
#include <BleKeyboard.h>

#define PIN_BTN   4          // 按键 → GND(下降沿触发)
#define PIN_LED   16

BleKeyboard bleKeyboard("21's Knob", "luowei", 88);

// 按键消息队列
static QueueHandle_t btnQueue;

// 中断回调(Arduino 标准写法,不需要 attachInterruptArg)
void IRAM_ATTR onBtn() {
  static uint32_t last = 0;
  uint32_t now = xTaskGetTickCountFromISR();
  if (now - last < 2) return;   // 2 tick ≈ 2 ms 防抖
  last = now;
  uint8_t dummy = 1;
  xQueueSendFromISR(btnQueue, &dummy, NULL);
}

void setup() {
  pinMode(PIN_BTN, INPUT_PULLUP); 
  pinMode(PIN_LED, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(PIN_BTN), onBtn, FALLING);

  btnQueue = xQueueCreate(8, sizeof(uint8_t));

  // NimBLE 已在库内启用,无需手动设置连接间隔;
  bleKeyboard.begin();
}

void loop() {
  uint8_t dummy;
  if (xQueueReceive(btnQueue, &dummy, portMAX_DELAY) == pdTRUE) {
    if (bleKeyboard.isConnected()) {
      bleKeyboard.write(KEY_LEFT_CTRL);
      delay(36);
      bleKeyboard.print(" ");
    }
    digitalWrite(PIN_LED, HIGH);
    vTaskDelay(pdMS_TO_TICKS(50));
    digitalWrite(PIN_LED, LOW);
  }
}

 

 

; 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:esp32dev]
platform = espressif32@4.1.0
board = esp32dev
framework = arduino

; ---------- CPU & 编译 ----------
; board_build.f_cpu    = 240000000L     ; 跑满 240 MHz
; board_build.f_flash  = 80000000L
; board_build.partitions = default_8MB.csv ; 如果板子 Flash ≥ 8 MB 可留

; ---------- 库 ----------
lib_deps =
    ; NimBLE 版 ESP32-BLE-Keyboard(比官方 Bluedroid 快)
    https://github.com/T-vK/ESP32-BLE-Keyboard.git#master

; ---------- 编译标志 ----------
build_flags =
    -DCORE_DEBUG_LEVEL=0              ; 关闭调试日志,减少延迟
    -DESP32_BLE_KEYBOARD_NIMBLE       ; 强制使用 NimBLE 栈
    ; -DCONFIG_BT_NIMBLE_MAX_CONNECTIONS=1
    ; -DCONFIG_BT_NIMBLE_HOST_BASED_PRIVACY=n
    ; -DCONFIG_BT_NIMBLE_DEBUG=0
    ; -DCONFIG_NIMBLE_CPP_DEBUG_LEVEL=0
    ; -DCONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME="\"21's Knob\""

; ---------- 上传 ----------
upload_speed = 921600
monitor_speed = 115200

 

 

连线图一句话总结:
按键一脚 → GPIO4,另一脚 → GND;LED 正极 → GPIO16,负极 → GND(串 330 Ω 电阻)。
────────────────────
1 微动开关(按键)
  • 开关公共端(COM) → GPIO4
  • 开关常闭端(NC 或 NO,无所谓) → GND
    (代码里 INPUT_PULLUP 已启用内部上拉,按下时 GPIO4 被拉到低电平,触发 FALLING 中断)
2 LED 指示灯
  • LED 正极(长脚) → GPIO16
  • LED 负极(短脚) → 330 Ω 电阻GND
    (3.3 V 供电,330 Ω 限流约 5 mA,足够亮且安全)
3 供电
  • ESP32 的 3V3GND 正常接好即可。
实物示意图(文字版)
 
复制
ESP32-S3 DevKit
┌─────────────┐
│ 3V3  GND  4 │   ← 按键一脚接 4,另一脚接 GND
│ 16         …│   ← 16 → 330 Ω → LED → GND
└─────────────┘
 
接好后通电,按下按钮即可在 PC 端收到一次 Ctrl 键,LED 闪 20 ms。

全部评论

·