ESP32 WiFi Scan Example
Introduction
ESP32 Wi-Fi Modes -
The ESP32 board can act as Wi-Fi Station, Access Point or both. To set the Wi-Fi mode, use WiFi.mode() and set the desired mode as argument:
WiFi.mode(WIFI_STA) - station mode: the ESP32 connects to an access point
WiFi.mode(WIFI_AP) - access point mode: stations can connect to the ESP32
WiFi.mode(WIFI_AP_STA) - access point and a station connected to another access point
Wi-Fi Station -
When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). Your can connect to ESP using the IP address assigned by router.
Access Point -
When you set your ESP32 board as an access point, it creates its own Wi-Fi network and you can be connect any device with Wi-Fi capabilities to your ESP32 board.
Wi-Fi Station + Access Point -
The ESP32 can be set as a Wi-Fi station and access point simultaneously.
Scan Wi-Fi Networks -
The ESP32 can scan nearby Wi-Fi networks within its Wi-Fi range.
Step 1: Connect Board to Laptop
Step 2: Scan Wi-Fi Networks Example Code
Select boar ESP32 DEV Module from Tools >> Boards menu, then select appropriate com port. Upload this program to ESP32.
#include "WiFi.h"
void setup()
{
Serial.begin(115200);
// First, set the Wi-Fi mode. If the ESP32 connected to another network (access point/hotspot) it must be in station mode.
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
}
void loop()
{
Serial.println("Scan start");
// WiFi.scanNetworks will return the number of networks found.
int n = WiFi.scanNetworks();
Serial.println("Scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
Serial.print(n);
Serial.println(" networks found");
Serial.println("Nr | SSID | RSSI | CH | Encryption");
for (int i = 0; i < n; ++i) {
// Print SSID and RSSI for each network found
Serial.printf("%2d",i + 1);
Serial.print(" | ");
Serial.printf("%-32.32s", WiFi.SSID(i).c_str());
Serial.print(" | ");
Serial.printf("%4ld", WiFi.RSSI(i));
Serial.print(" | ");
Serial.printf("%2ld", WiFi.channel(i));
Serial.print(" | ");
switch (WiFi.encryptionType(i))
{
case WIFI_AUTH_OPEN:
Serial.print("open");
break;
case WIFI_AUTH_WEP:
Serial.print("WEP");
break;
case WIFI_AUTH_WPA_PSK:
Serial.print("WPA");
break;
case WIFI_AUTH_WPA2_PSK:
Serial.print("WPA2");
break;
case WIFI_AUTH_WPA_WPA2_PSK:
Serial.print("WPA+WPA2");
break;
case WIFI_AUTH_WPA2_ENTERPRISE:
Serial.print("WPA2-EAP");
break;
case WIFI_AUTH_WPA3_PSK:
Serial.print("WPA3");
break;
case WIFI_AUTH_WPA2_WPA3_PSK:
Serial.print("WPA2+WPA3");
break;
case WIFI_AUTH_WAPI_PSK:
Serial.print("WAPI");
break;
default:
Serial.print("unknown");
}
Serial.println();
delay(10);
}
}
Serial.println("");
// Delete the scan result to free memory for code below.
WiFi.scanDelete();
// Wait a bit before scanning again.
delay(5000);
}