0

I have an issue with WiFi.begin() in esp8266-12F.

I'm going to connect the ESP8266 with the specific Access Point in the loop() not in the setup().

I want if a specific AP is available, ESP8266 would connect to it. In the below code, I supposed to connect to the "abc" AP and turns on an LED and if there is no connection, it turns the LED off, but WiFi.begin("abc", "123456789"); is not working.

What I have to do in this case?

setup(){

}

loop(){

    if (WiFi.status() != WL_CONNECTED){
        WiFi.disconnect();
        WiFi.mode(WIFI_STA);
        WiFi.begin("abc", "123456789");
        digitalWrite(5, HIGH);
    } else {
        digitalWrite(5, LOW);
    }

}
Community
  • 1
  • 1
Reza Hadipour
  • 52
  • 1
  • 9

2 Answers2

0

I would use the standard code for building a WiFi connection in the setup() and just set the led as HIGH/LOW in the loop() according to WiFi.status(). Reconnect should be handled automatically...

PrfctByDsgn
  • 1,022
  • 1
  • 14
  • 18
0

No point in adding WiFi-disconnect() if you're not connected to any AP at the moment. Just connect to the AP on the setup and leave on the loop() the if (WiFi.status() != WL_CONNECTED). The ESP reconnects itself to the AP when available.

setup(){
Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    WiFi.setAutoConnect(true);
    Serial.print("Connecting to ");
    Serial.print(ssid);
    int attempt = 0;
    while(WiFi.status() != WL_CONNECTED && attempt<150){  //Connecting to Wi-Fi
        delay(100);
        Serial.print(".");
        attempt++;
    }
    if(WiFi.status() == WL_CONNECTED){
        Serial.println("");
        Serial.println("WiFi Connected!");
        Serial.print("Local IP: ");
        Serial.println(WiFi.localIP());
    }
    if(attempt == 150){
        Serial.println("Failed to connect to WiFi...");
    }
}

loop(){

if(WiFi.status() != WL_CONNECTED){
    digitalWrite(5,HIGH);
}else{
    digitalWrite(5,LOW);
}

}

But for the love of good code otimization use a flag to prevent the digitalWrite to happen hundreds of times per second

PmmZenha
  • 155
  • 2
  • 9