1+ /* *
2+ * Example of continuous scanning for BLE advertisements.
3+ * This example will scan for scanTime (seconds) and report all advertisements on the serial monitor.
4+ *
5+ * Note the configuration options in the build_opt.h file.
6+ * More BLE examples can be found in the NimBLE-Arduino examples: https://github.com/h2zero/NimBLE-Arduino.
7+ *
8+ * For further BLE documentation see: https://h2zero.github.io/NimBLE-Arduino
9+ */
10+
11+ #include < Arduino.h>
12+ #include " NimBLEDevice.h"
13+
14+ NimBLEScan* pBLEScan;
15+ uint32_t scanTime = 30 ; // Scan duration in seconds (0 = forever)
16+
17+ // Callback class for received advertisements
18+ class MyAdvertisedDeviceCallbacks : public NimBLEAdvertisedDeviceCallbacks {
19+ void onResult (NimBLEAdvertisedDevice* advertisedDevice) {
20+ Serial.printf (" Advertised Device: %s \n " , advertisedDevice->toString ().c_str ());
21+ }
22+ };
23+
24+ void setup () {
25+ Serial.begin (115200 );
26+ Serial.println (" Scanning..." );
27+
28+ // Initialize the BLE stack
29+ NimBLEDevice::init (" " );
30+
31+ // Create new scan instance
32+ pBLEScan = NimBLEDevice::getScan ();
33+
34+ // Set the callback for when devices are discovered, no duplicates.
35+ pBLEScan->setAdvertisedDeviceCallbacks (new MyAdvertisedDeviceCallbacks (), false );
36+
37+ // Set active scanning, this will get scan response data from the advertiser.
38+ pBLEScan->setActiveScan (true );
39+
40+ // Set how often the scan occurs/switches channels; in milliseconds,
41+ pBLEScan->setInterval (97 );
42+
43+ // How long to scan during the interval; in milliseconds.
44+ pBLEScan->setWindow (37 );
45+
46+ // Do not store the scan results, use callback only.
47+ pBLEScan->setMaxResults (0 );
48+ }
49+
50+ void loop () {
51+ // When the scan stops, restart it. This will cause duplicate devices to be reported again.
52+ if (pBLEScan->isScanning () == false ) {
53+ // Start scan with: duration = scanTime (seconds), no scan ended callback, not a continuation of a previous scan.
54+ pBLEScan->start (scanTime, nullptr , false );
55+ }
56+
57+ // Short delay to allow the stack to reset states.
58+ delay (100 );
59+ }
0 commit comments