I want to scan continuously for other Bluetooth devices with my ESP32 using BLE. The scan method only accepts integers larger than 0, such as scan->start(1, false). However I want the results to be more "responsive" and a 1-second scanning duration is too long. This is my sample code:
#include <Arduino.h>
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEScan.h>
#include <string>
#include <iostream>
const int PIN = 2;
const int CUTOFF = -40;
BLEScan* scan;
#define SERVICE_UUID "f5aeb701-4395-4387-b8d4-e1f542b05151"
#define CHARACTERISTIC_UUID "b2bd617f-6f78-45e7-bfdd-3edf29a5661a"
void setup() {
pinMode(PIN, OUTPUT);
BLEDevice::init("ESP32 GrooveBrick");
Serial.begin(9600);
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
scan = BLEDevice::getScan();
scan->setActiveScan(true);
/*!< Scan interval. This is defined as the time interval from
when the Controller started its last LE scan until it begins the subsequent LE scan.
Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms)
Time = N * 0.625 msec
Time Range: 2.5 msec to 10.24 seconds*/
scan->setInterval(100); //interval (how often there is a scan)
/*!< Scan window. The duration of the LE scan. LE_Scan_Window
shall be less than or equal to LE_Scan_Interval
Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms)
Time = N * 0.625 msec
Time Range: 2.5 msec to 10240 msec */
scan->setWindow(99); // window (how long the scans are) must be <= interval
BLEDevice::startAdvertising();
}
void loop() {
BLEScanResults results = scan->start(1, true);
int best = CUTOFF;
std::cout << "Scanning!" << "\n";
for (int i = 0; i < results.getCount(); i++) {
BLEAdvertisedDevice device = results.getDevice(i);
std::cout << "Found BT-device: " << device.getName() << " RSSI: " << std::to_string(device.getRSSI()) << "\n";
int rssi = device.getRSSI();
if (rssi > best) {
best = rssi;
}
}
digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
scan->clearResults(); // delete results fromBLEScan buffer to release memory
}