Search code examples
arduinowifiesp32arduino-ideesp8266wifi

My ESP32 is scanning all the nearby WiFi Networks but it does not connect to my WiFi Router using Arduino IDE (Return Value of WiFi.status API = 6)


I am trying to connect my ESP32 to my Wifi Router using Arduino IDE but it is not connecting & giving a connection failed or disconnected status. I also confirmed it is scanning all the available Wifi Networks but not connecting to my router. I even tried with another ESP32 board but the problem is still there.



I tried this code below. This code would scan/give the available Wifi networks and it did. Also, I was expecting this code to run smoothly but my ESP32 won't connect to my Wifi router.

#include<WiFi.h>

const char *ssid = "my_SSID";  
const char *password = "my_Password";

void setup()
{
    Serial.begin(115200);
    delay(2000);
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);

    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");}

    // Connect to my network.
    WiFi.begin(ssid,password);     

    // Check Status of your WiFi Connection
    int x = WiFi.status(); // If x=3 (Connected to Network) & If x=6 (Disconnected from Network)
    Serial.print("WiFi Connection Status is ");
    Serial.println(x);
    
    while(WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("WiFi Connection Failed...");
        WiFi.disconnect();
        WiFi.reconnect();  }

    //Print local IP address and start web server
      Serial.println("\nConnecting");
      Serial.println("");
      Serial.println("WiFi connected.");
      Serial.println("ESP32 IP address: ");
      Serial.println(WiFi.localIP());
}

void loop() {}

1st image shows the output of my serial monitor. 2nd inamge shows the return value for WiFi.status function


Solution

  • Try this code:

    #include<WiFi.h>
    
    const char *ssid = "YourSSID";  
    const char *password = "YourPassword";
            
    void initWiFi() {
          WiFi.mode(WIFI_STA);
          WiFi.begin(ssid, password);
          Serial.print("Connecting to WiFi ..");
          while (WiFi.status() != WL_CONNECTED) {
            Serial.print('.');
            delay(1000);
          }
          Serial.println(WiFi.localIP());
        }
        
        void setup() {
          Serial.begin(115200);
          initWiFi();
          Serial.print("RRSI: ");
          Serial.println(WiFi.RSSI());
        }
        
        void loop() {
          // put your main code here, to run repeatedly:
        }