如何配置NodeMCU内置蓝牙?含设备命名及密码设置需求
NodeMCU(ESP32)内置蓝牙配置方案
前提说明
NodeMCU只有基于ESP32的型号才内置蓝牙,ESP8266无内置蓝牙模块,请确认你的设备为ESP32系列。
1. 设置蓝牙名称为自定义序列号
方案1:Arduino框架快速实现
通过Arduino代码读取预存的序列号(支持批量烧录写入),并将其设为蓝牙设备名称:
- 优先用NVS(非易失性存储)存储序列号,比EEPROM更可靠,批量烧录时可通过工具给每台设备写入唯一序列号。
- 经典蓝牙(SPP)示例代码:
#include <BluetoothSerial.h> #include <Preferences.h> BluetoothSerial SerialBT; Preferences prefs; String deviceSerial; void setup() { // 初始化NVS并读取序列号 prefs.begin("device_config", true); deviceSerial = prefs.getString("serial_num", "DEFAULT_SERIAL"); prefs.end(); // 以序列号为名称启动蓝牙 SerialBT.begin(deviceSerial); Serial.println("Bluetooth started with name: " + deviceSerial); } void loop() { // 蓝牙与串口的数据转发逻辑(可替换为和Android App的参数交互逻辑) if (SerialBT.available()) { Serial.write(SerialBT.read()); } if (Serial.available()) { SerialBT.write(Serial.read()); } }
- 批量烧录时,可通过
esptool.py或Arduino批量烧录工具,给不同设备写入带唯一序列号的NVS分区文件,无需逐台修改代码。
方案2:ESP-IDF框架量产级实现
在ESP-IDF中通过动态配置蓝牙名称,结合批量烧录的自定义数据分区实现唯一名称:
- 核心代码片段:
#include <stdio.h> #include "nvs_flash.h" #include "esp_bt.h" #include "esp_bt_main.h" #include "esp_gap_bt_api.h" #define DEVICE_SERIAL_KEY "serial_num" static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) { // 蓝牙GAP事件回调处理 } void app_main() { nvs_flash_init(); esp_bt_controller_init(); esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT); esp_bluedroid_init(); esp_bluedroid_enable(); // 从NVS读取序列号 nvs_handle_t nvs_handle; nvs_open("device_config", NVS_READONLY, &nvs_handle); char serial_num[32] = {0}; size_t len = sizeof(serial_num); nvs_get_str(nvs_handle, DEVICE_SERIAL_KEY, serial_num, &len); nvs_close(nvs_handle); // 设置蓝牙设备名称 esp_bt_gap_set_device_name(serial_num); esp_bt_gap_register_callback(esp_bt_gap_cb); }
2. 设置蓝牙配对密码
经典蓝牙(SPP)配对密码设置
- Arduino框架下,直接调用
setPin方法:
// 在setup函数中添加 SerialBT.setPin("1234"); // 支持1-16位密码,可自定义
- ESP-IDF框架下,通过
esp_bt_gap_set_pin配置:
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_FIXED; esp_bt_pin_code_t pin_code = {1,2,3,4}; esp_bt_gap_set_pin(pin_type, 4, pin_code);
注意:配对密码仅适用于经典蓝牙模式,BLE模式采用配对密钥(如Passkey Entry),需在Android App中对应实现配对逻辑。
BLE模式安全配对配置
如果使用BLE蓝牙,可配置安全参数强制配对验证:
#include <BLEDevice.h> #include <BLEServer.h> BLEServer* pServer = NULL; class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) {}; void onDisconnect(BLEServer* pServer) {} }; void setup() { BLEDevice::init(deviceSerial); // 用序列号作为BLE设备名称 pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // 配置BLE安全参数,要求安全连接并绑定 BLESecurity *pSecurity = new BLESecurity(); pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND); pSecurity->setCapability(ESP_IO_CAP_OUT); // 根据设备输入输出能力调整 }
批量烧录序列号方法
- 使用
esptool.py批量写入NVS数据:- 为每台设备生成包含唯一序列号的NVS二进制文件
- 执行命令:
esptool.py --port COMx write_flash 0x300000 serial_nvs.bin(地址需匹配你的分区表)
- 也可通过ESP-IDF的
nvs_partition_generator.py工具生成带不同序列号的NVS分区文件,再批量烧录。
内容的提问来源于stack exchange,提问作者Anıl Köksal
相关产品推荐
相关产品推荐

