WiFi

The article provides a comprehensive guide on using ESP32 for WiFi network scanning and configuration, detailing both synchronous and asynchronous scanning methods, as well as how to configure WiFi via a web page for easy and flexible network connections.

WiFi

Example: WiFi Scan

WiFi Scan has both synchronous and asynchronous search modes. This example uses synchronous scanning. The drawback is that it runs in blocking mode by default, meaning the program will scan for WiFi and nothing else can be done during this time. You can switch to asynchronous mode by modifying the parameters.

In this example, the WiFi is first set to station mode. If the device is in AP mode and is connected to other devices, the connection will be disconnected.

Then, the WiFi.scanNetworks() function is called to scan for WiFi networks. If networks are found, their information will be printed out.

Hardware Requirements:

Example Code:

/*
 *  This example demonstrates how to scan for WiFi networks.
 *  The API is almost identical to the WiFi Shield library, 
 *  with the most obvious difference being the inclusion of different header files:
 */
#include "WiFi.h"

void setup()
{
    Serial.begin(115200);

    // Set WiFi to station (client) mode. If the device is in AP (hotspot) mode and connected, it will disconnect.
    WiFi.mode(WIFI_STA);  // Set to Station mode
    WiFi.disconnect();    // Disconnect from the current WiFi connection
    delay(100);

    Serial.println("Setup done");
}

void loop()
{
    Serial.println("scan start");

    // The WiFi.scanNetworks() function 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");
        for (int i = 0; i < n; ++i) {
            // Print the SSID (Service Set Identifier) and RSSI (Received Signal Strength Indicator) of each network
            Serial.print(i + 1);
            Serial.print(": ");
            Serial.print(WiFi.SSID(i)); // Print network name
            Serial.print(" (");
            Serial.print(WiFi.RSSI(i)); // Print signal strength
            Serial.print(")");

            // Output " " (open network) or "*" (encrypted network) based on the encryption type
            // WIFI_AUTH_OPEN represents no encryption (no password required)
            Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");            
            delay(10);
        }
    }
    Serial.println("");

    // Wait for a while before scanning again
    delay(5000);
}

Result: The scanned WiFi networks are printed out from the serial port.

Example: Web Page Configuration

Initially, the WiFi device is in AP mode, and the default IP address is 192.168.4.1. By accessing this IP via a web page, users can connect to the AP. In the input fields, users enter the SSID and password of their router's WiFi. Once the WiFi device receives this information, it switches to STA mode and connects to the network using the provided details. The advantage of this method is a 100% success rate, but it requires a button to put the device into configuration mode.

Advantages of Web Page Configuration:

  • Direct input makes configuration simple, the process is clear, and the success rate is high.
  • The router or hotspot to be connected to is not restricted and does not require an internet connection.
  • No need to add additional interfaces to the system, making it suitable for closed or inconvenient scenarios where extra interfaces cannot be exposed.
  • The configuration can be done using any device that supports WiFi and a browser, making it very flexible and practical.

Hardware Requirements:

Example Code:

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <esp_wifi.h>

const char* AP_SSID  = "Edge101_"; // Hotspot name
String wifi_ssid = "";
String wifi_pass = "";
String scanNetworksID = "";// Used to store scanned WiFi

#define ROOT_HTML  "<!DOCTYPE html><html><head><title>WIFI Config by DFRobot</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head><style type=\"text/css\">.input{display: block; margin-top: 10px;}.input span{width: 100px; float: left; float: left; height: 36px; line-height: 36px;}.input input{height: 30px;width: 200px;}.btn{width: 120px; height: 35px; background-color: #000000; border:0px; color:#ffffff; margin-top:15px; margin-left:100px;}</style><body><form method=\"GET\" action=\"connect\"><label class=\"input\"><span>WiFi SSID</span><input type=\"text\" name=\"ssid\"></label><label class=\"input\"><span>WiFi PASS</span><input type=\"text\"  name=\"pass\"></label><input class=\"btn\" type=\"submit\" name=\"submit\" value=\"Submit\"> <p><span> Nearby wifi:</P></form>"

WebServer server(80);

#define RESET_PIN   38  // GPIO 38 User Key for deleting WiFi information

void setup() {

  Serial.begin(115200);
  pinMode(RESET_PIN, INPUT_PULLUP);

  // Connect to WiFi
  if (!AutoConfig())
  {
    wifi_Config();
  }

  // Used to delete stored WiFi
  if (digitalRead(RESET_PIN) == LOW) {
    Serial.println("Delete WiFi and restart");
    delay(1000);
    esp_wifi_restore();
    delay(10);
    ESP.restart();  // Reset ESP32
  }
}

void loop() {
  server.handleClient();
  while (WiFi.status() == WL_CONNECTED) {
    // WIFI is connected
  }
}

// For configuring WiFi
void wifi_Config()
{
  Serial.println("scan start");
  // Scan for nearby WiFi networks
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
    scanNetworksID = "no networks found";
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
      scanNetworksID += "<P>" + WiFi.SSID(i) + "</P>";
      delay(10);
    }
  }
  Serial.println("");

  WiFi.mode(WIFI_AP); // Set to AP mode
  boolean result = WiFi.softAP(AP_SSID, ""); // Start WiFi hotspot
  if (result)
  {
    IPAddress myIP = WiFi.softAPIP();
    // Print related information
    Serial.println("");
    Serial.print("Soft-AP IP address = ");
    Serial.println(myIP);
    Serial.println(String("MAC address = ")  + WiFi.softAPmacAddress().c_str());
    Serial.println("waiting ...");
  } else {  // Failed to start hotspot
    Serial.println("WiFiAP Failed");
    delay(3000);
    ESP.restart();  // Reset ESP32
  }

  if (MDNS.begin("esp32")) {
    Serial.println("MDNS responder started");
  }

  // Homepage
  server.on("/", []() {
    server.send(200, "text/html", ROOT_HTML + scanNetworksID + "</body></html>");
  });

  // Connect
  server.on("/connect", []() {

    server.send(200, "text/html", "<html><body><font size=\"10\">Success, WiFi connecting...<br />Please close this page manually.</font></body></html>");

    WiFi.softAPdisconnect(true);
    // Get the entered WiFi SSID and password
    wifi_ssid = server.arg("ssid");
    wifi_pass = server.arg("pass");
    server.close();
    WiFi.softAPdisconnect();
    Serial.println("WiFi Connect SSID:" + wifi_ssid + "  PASS:" + wifi_pass);

    // Set to STA mode and connect to WiFi
    WiFi.mode(WIFI_STA);
    WiFi.begin(wifi_ssid.c_str(), wifi_pass.c_str());
    uint8_t Connect_time = 0; // Used for connection timeout, reset the device if it takes too long
    while (WiFi.status() != WL_CONNECTED) {  // Wait for WiFi connection
      delay(500);
      Serial.print(".");
      Connect_time++;
      if (Connect_time > 80) {  // Long connection time, reset the device
        Serial.println("Connection timeout, check if input is correct or try again later!");
        delay(3000);
        ESP.restart();
      }
    }
    Serial.println("");
    Serial.println("WIFI Config Success");
    Serial.printf("SSID:%s", WiFi.SSID().c_str());
    Serial.print("  LocalIP:");
    Serial.print(WiFi.localIP());
    Serial.println("");

  });
  server.begin();
}

// For automatic WiFi connection on power-up
bool AutoConfig()
{
  WiFi.begin();
  for (int i = 0; i < 20; i++)
  {
    int wstatus = WiFi.status();
    if (wstatus == WL_CONNECTED)
    {
      Serial.println("WIFI SmartConfig Success");
      Serial.printf("SSID:%s", WiFi.SSID().c_str());
      Serial.printf(", PSW:%s\r\n", WiFi.psk().c_str());
      Serial.print("LocalIP:");
      Serial.print(WiFi.localIP());
      Serial.print(" ,GateIP:");
      Serial.println(WiFi.gatewayIP());
      return true;
    }
    else
    {
      Serial.print("WIFI AutoConfig Waiting......");
      Serial.println(wstatus);
      delay(1000);
    }
  }
  Serial.println("WIFI AutoConfig Failed!" );
  return false;
}

Was this article helpful?

TOP