#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
#define BT_DISCOVER_TIME 10000
static bool btScanAsync = true;
static bool btScanSync = true;
void btAdvertisedDeviceFound(BTAdvertisedDevice *pDevice) {
Serial.printf("Found a device asynchronously: %s\n", pDevice->toString().c_str());
}
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
if (btScanAsync) {
Serial.print("Starting asynchronous discovery... ");
if (SerialBT.discoverAsync(btAdvertisedDeviceFound)) {
Serial.println("Findings will be reported in \"btAdvertisedDeviceFound\"");
delay(10000);
Serial.print("Stopping discoverAsync... ");
SerialBT.discoverAsyncStop();
Serial.println("stopped");
} else {
Serial.println("Error on discoverAsync f.e. not working after a \"connect\"");
}
}
if (btScanSync) {
Serial.println("Starting synchronous discovery... ");
BTScanResults *pResults = SerialBT.discover(BT_DISCOVER_TIME);
if (pResults) {
pResults->dump(&Serial);
} else {
Serial.println("Error on BT Scan, no result!");
}
}
}
void loop() {
delay(100);
}
输出
设备已启动,现在可以与蓝牙配对了!
开始异步发现...发现结果将在以下位置报告 “btAdvertizedDeviceFound”
异步发现设备:名称:Printer001,地址: dc:0d:30:c1:7e:04,鳕鱼:0x040680,RSSI:-48
停止discoverAsync...已停止
开始同步发现...
转储扫描结果:1
- 1:名称:Printer001,地址:dc:0d:30:c1:7e:04,cod:0x040680,rssi:-49
-- 转储完成--
您好,想将我的 esp32 连接到“Printer001”,但该打印机的配对代码为“1234”。请帮助我,我尝试通过 SerialBT.connect() 连接它,但它不起作用,因为我不知道如何将配对代码设置为 esp32
我相信你想像这个例子中那样使用setPin:
uint8_t address[6] = { 0x20, 0x13, 0x01, 0x18, 0x02, 0x26 }; // Change for your address
bool connected;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test");
SerialBT.setPin("1234", 4);
connected = SerialBT.connect(address);