#include <BLEDevice.h>
BLERemoteDevice* detectedDevice;
void setup() {
Serial.begin(115200);
// Set the callback function for BLE scans
BLEDevice::setScanCallback(callback);
// Start scanning for BLE devices
BLEDevice::startScanning();
}
void loop() {
// Handle Bluetooth events in the background
BLEDevice::poll();
// Print information about the detected device (if any)
if (detectedDevice) {
String address = detectedDevice->getAddress();
String name = detectedDevice->getName();
Serial.print("Address: ");
Serial.println(address);
Serial.print("Name: ");
if (name.isEmpty()) {
Serial.println("<No Name>");
} else {
Serial.println(name);
}
Serial.println("---");
// You can optionally clear the detected device for subsequent scans
detectedDevice = nullptr;
}
}
// Callback function for BLE scans
void callback(BLEScanResults results) {
if (results.advertisedDevice) {
BLEAdvertisingData advData = results.advertisedDevice.getAdvertisingData();
// You can filter devices based on specific criteria here (e.g., name, service UUIDs)
// This example simply stores the first detected device
if (!detectedDevice) {
detectedDevice = &results.advertisedDevice;
}
}
}