Skip to content

Instantly share code, notes, and snippets.

@jericbas
Created May 7, 2026 11:23
Show Gist options
  • Select an option

  • Save jericbas/0dffffb5df100f54ca6d174bed5f0b6f to your computer and use it in GitHub Desktop.

Select an option

Save jericbas/0dffffb5df100f54ca6d174bed5f0b6f to your computer and use it in GitHub Desktop.
BLE finder
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
// Configuration
int scanTime = 5;
int RSSI_THRESHOLD = -55; // Anything stronger than -55 is considered "Very Near"
// Variables to track the "Winner" of each scan
String strongestMac = "";
int strongestRSSI = -999;
bool foundNearDevice = false;
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
int currentRSSI = advertisedDevice.getRSSI();
// We only care about devices that are stronger (closer) than our current best
if (currentRSSI > strongestRSSI) {
strongestRSSI = currentRSSI;
strongestMac = advertisedDevice.getAddress().toString().c_str();
// If it passes our threshold, we mark it as a potential "constant" neighbor
if (currentRSSI >= RSSI_THRESHOLD) {
foundNearDevice = true;
}
}
}
};
void setup() {
Serial.begin(115200);
Serial.println("--- Starting Nearest Device Tracker ---");
Serial.printf("Filter: Only highlighting devices stronger than %d dBm\n", RSSI_THRESHOLD);
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
pBLEScan->setInterval(100);
pBLEScan->setWindow(99);
}
void loop() {
// Reset scan variables
strongestRSSI = -999;
strongestMac = "";
foundNearDevice = false;
Serial.println("Scanning for nearest neighbor...");
BLEScan* pBLEScan = BLEDevice::getScan();
BLEScanResults* foundDevices = pBLEScan->start(scanTime, false);
// Output the winner of this scan cycle
if (strongestMac != "") {
Serial.println("========================================");
if (foundNearDevice) {
Serial.println(">>> [TARGET FOUND] - CONSTANTLY NEARBY <<<");
} else {
Serial.println("Nearest device (but not close enough):");
}
Serial.printf("MAC: %s | RSSI: %d\n", strongestMac.c_str(), strongestRSSI);
// Simple visual distance indicator
Serial.print("Proximity: ");
int bars = map(strongestRSSI, -100, -30, 1, 20);
for(int i=0; i<bars; i++) Serial.print("|");
Serial.println();
Serial.println("========================================\n");
} else {
Serial.println("No devices found in this cycle.");
}
pBLEScan->clearResults();
delay(1000); // Wait 1 second before next scan
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment