Skip to content

Commit 95de525

Browse files
authored
Refactor WiFi scan example (#7655)
1 parent c656266 commit 95de525

File tree

1 file changed

+38
-24
lines changed

1 file changed

+38
-24
lines changed

libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino

+38-24
Original file line numberDiff line numberDiff line change
@@ -3,43 +3,57 @@
33
The API is almost the same as with the WiFi Shield library,
44
the most obvious difference being the different file you need to include:
55
*/
6-
#include "ESP8266WiFi.h"
6+
7+
#include <ESP8266WiFi.h>
78

89
void setup() {
910
Serial.begin(115200);
11+
Serial.println(F("\nESP8266 WiFi scan example"));
1012

11-
// Set WiFi to station mode and disconnect from an AP if it was previously connected
13+
// Set WiFi to station mode
1214
WiFi.mode(WIFI_STA);
15+
16+
// Disconnect from an AP if it was previously connected
1317
WiFi.disconnect();
1418
delay(100);
15-
16-
Serial.println("Setup done");
1719
}
1820

1921
void loop() {
20-
Serial.println("scan start");
22+
String ssid;
23+
int32_t rssi;
24+
uint8_t encryptionType;
25+
uint8_t* bssid;
26+
int32_t channel;
27+
bool hidden;
28+
int scanResult;
2129

22-
// WiFi.scanNetworks will return the number of networks found
23-
int n = WiFi.scanNetworks();
24-
Serial.println("scan done");
25-
if (n == 0) {
26-
Serial.println("no networks found");
27-
} else {
28-
Serial.print(n);
29-
Serial.println(" networks found");
30-
for (int i = 0; i < n; ++i) {
31-
// Print SSID and RSSI for each network found
32-
Serial.print(i + 1);
33-
Serial.print(": ");
34-
Serial.print(WiFi.SSID(i));
35-
Serial.print(" (");
36-
Serial.print(WiFi.RSSI(i));
37-
Serial.print(")");
38-
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
39-
delay(10);
30+
Serial.println(F("Starting WiFi scan..."));
31+
32+
scanResult = WiFi.scanNetworks(/*async=*/false, /*hidden=*/true);
33+
34+
if (scanResult == 0) {
35+
Serial.println(F("No networks found"));
36+
} else if (scanResult > 0) {
37+
Serial.printf(PSTR("%d networks found:\n"), scanResult);
38+
39+
// Print unsorted scan results
40+
for (int8_t i = 0; i < scanResult; i++) {
41+
WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel, hidden);
42+
43+
Serial.printf(PSTR(" %02d: [CH %02d] [%02X:%02X:%02X:%02X:%02X:%02X] %ddBm %c %c %s\n"),
44+
i,
45+
channel,
46+
bssid[0], bssid[1], bssid[2],
47+
bssid[3], bssid[4], bssid[5],
48+
rssi,
49+
(encryptionType == ENC_TYPE_NONE) ? ' ' : '*',
50+
hidden ? 'H' : 'V',
51+
ssid.c_str());
52+
delay(0);
4053
}
54+
} else {
55+
Serial.printf(PSTR("WiFi scan error %d"), scanResult);
4156
}
42-
Serial.println("");
4357

4458
// Wait a bit before scanning again
4559
delay(5000);

0 commit comments

Comments
 (0)