Site icon techtutorialsx

ESP8266: Scanning WiFi Networks

The objective of this post is to explain how to scan the surrounding WiFi networks with the ESP8266.


The code

The code for this tutorial will be very simple and since we only want to scan and get some information about the surrounding WiFi networks, we will do all the coding on the setup function. So, we will leave the main loop empty.

First of all, we include the ESP8266WiFi library, which will make available the functionality needed for the ESP8266 to interact with the WiFi networks. We can remember from previous posts that this is also the library needed for us to connect to a WiFi network.

#include "ESP8266WiFi.h"

In the setup function, we start by  opening a serial connection, so we can send the data to the Arduino IDE serial console.

Next, to scan the networks, we call the scanNetworks method on the WiFi object of the library we included. This method will return the number of networks discovered [1].

Note that this method can be called with two additional arguments, one that indicates the scanning should be done asynchronously, and another to show networks with hidden SSID [1]. More details about these functionalities can be found here.

int numberOfNetworks = WiFi.scanNetworks();

Now, to get each network SSID, we just need to call the SSID method, which receives as argument the index of one of the previously discovered networks. In the example bellow, we are getting this parameter for the first network of the list. Naturally, you should check first if any network was discovered

Serial.println(WiFi.SSID(0));

We can also get the RSSI (Received Signal Strength Indicator) of each network by calling the RSSI method on the WiFi object, again passing as input the index of the network.

Serial.println(WiFi.RSSI(0));

The complete code is shown bellow, which includes the iteration over the discovered networks and printing of these indicators to the serial port.

#include "ESP8266WiFi.h"

void setup() {

  Serial.begin(115200);

  int numberOfNetworks = WiFi.scanNetworks();

  for(int i =0; i<numberOfNetworks; i++){

      Serial.print("Network name: ");
      Serial.println(WiFi.SSID(i));
      Serial.print("Signal strength: ");
      Serial.println(WiFi.RSSI(i));
      Serial.println("-----------------------");

  }

}

void loop() {}

To test the code just upload it to the ESP8266 and open the serial console. You should get something similar to figure 1.

Figure 1 – Output of the program.

Note that there are more functionalities associated with the scanning of surrounding WiFi networks, which can be seen here.


Related Posts

ESP8266: Connecting to a WiFi Network


References

[1]https://github.com/esp8266/Arduino/blob/4897e0006b5b0123a2fa31f67b14a3fff65ce561/doc/esp8266wifi/scan-class.md


Technical details

Exit mobile version