简体   繁体   English

如何在 ESP8266 中通过 loop() 连接到 AP

[英]How to connect to the AP in loop() in ESP8266

I have an issue with WiFi.begin() in esp8266-12F.我在 esp8266-12F 中遇到WiFi.begin()问题。

I'm going to connect the ESP8266 with the specific Access Point in the loop() not in the setup() .我要将 ESP8266 与loop()的特定接入点连接,而不是在setup()

I want if a specific AP is available, ESP8266 would connect to it.我想如果特定的 AP 可用,ESP8266 会连接到它。 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");在下面的代码中,我应该连接到“abc”AP 并打开一个 LED,如果没有连接,它会关闭 LED,但是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);
    }

}

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() .我将使用标准代码在setup()setup() WiFi 连接,并根据WiFi.status()loop() WiFi.status()设置为高/低。 Reconnect should be handled automatically...重新连接应该自动处理...

No point in adding WiFi-disconnect() if you're not connected to any AP at the moment.如果您目前未连接到任何 AP,则添加WiFi-disconnect()毫无意义。 Just connect to the AP on the setup and leave on the loop() the if (WiFi.status() != WL_CONNECTED) .只需连接到设置上的 AP 并在loop()上保留if (WiFi.status() != WL_CONNECTED) The ESP reconnects itself to the AP when available. ESP 在可用时将自身重新连接到 AP。

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但是对于好的代码优化的热爱使用一个标志来防止 digitalWrite 每秒发生数百次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM