get_RSSI_Device_Name.ino 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <BLEDevice.h>
  2. #include <BLEUtils.h>
  3. #include <BLEScan.h>
  4. #include <BLEAdvertisedDevice.h>
  5. int scanTime = 10; // detik
  6. BLEScan *pBLEScan;
  7. class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  8. void onResult(BLEAdvertisedDevice advertisedDevice) {
  9. Serial.print("Address: ");
  10. Serial.print(advertisedDevice.getAddress().toString().c_str());
  11. Serial.print(" | Name: ");
  12. if (advertisedDevice.haveName()) {
  13. Serial.print(advertisedDevice.getName().c_str());
  14. } else {
  15. Serial.print("(No name)");
  16. }
  17. Serial.print(" | RSSI: ");
  18. Serial.println(advertisedDevice.getRSSI());
  19. }
  20. };
  21. void setup() {
  22. Serial.begin(115200);
  23. Serial.println("Scanning...");
  24. BLEDevice::init("");
  25. pBLEScan = BLEDevice::getScan(); // create new scan
  26. pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  27. pBLEScan->setActiveScan(true); // penting: agar dapat Scan Response (nama)
  28. pBLEScan->setInterval(100);
  29. pBLEScan->setWindow(99); // harus <= interval
  30. }
  31. void loop() {
  32. BLEScanResults *foundDevices = pBLEScan->start(scanTime, false);
  33. Serial.printf("Scan done! Devices found: %d\n", foundDevices->getCount());
  34. pBLEScan->clearResults(); // hapus hasil scan biar memori gak penuh
  35. delay(3000);
  36. }