我在为 NodeMCU 1.0 (ESP-12E) 编写草图时遇到意外行为。
作为我的
void setup()
的一部分,我尝试在连接到 WiFi 时显示一些计数器。这个想法是显示每秒增加一的计数器。然而,将脚本上传到开发板后,计数器每大约 8 秒“滴答”一次 (1000+7000)。
我已经玩了一会儿了,对我来说,它看起来像是在重复循环之前增加了额外的 7 秒
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
int seconds = 0;
void setup() {
while (WiFiMulti.run() != WL_CONNECTED) {
lcd.clear();
lcd.print(seconds++);
lcd.print(" ");
delay(1000); // < Here I'm getting _additional_ ~7sec delay before loop repeats.
}
}
如果我将条件从
(WiFiMulti.run() != WL_CONNECTED)
替换为 (seconds<=10)
,一切都会正常工作。这就是为什么我倾向于认为问题纯粹在于WiFiMulti.run
。有人能指出我正确的方向吗?
更新: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#quick-start
我已经切换到:
WiFi.begin("SSID", "PASSWD");
while (WiFi.status() != WL_CONNECTED)
{
...
而且效果很好。现在挖掘 ESP8266WiFiMulti 的文档。
取决于 ESP8266WiFiMulti 实现以及它是否实现为完全非阻塞。
一种尝试方法是将代码转移到循环()而不是设置中,这也会显示连接是否已丢失以及您是否正在重新连接。这是一个非常快速的粗略示例,应该以非阻塞方式工作,未经测试,只是为了给您一个总体思路。
unsigned long wifi_check = 0; // we will use this to check every 30 sec if we are connected
unsigned long wifi_connection_counter = 0;//used to count every second whilst we are connecting
bool first_connect = 1; //is this the first time we are connecting
int seconds = 0;
void setup(){
if(wifiMulti.run() != WL_CONNECTED) {
lcd.clear();
lcd.print("Connecting to WiFi");
lcd.print(" ");
}else{
first_connect = 0; //we are connected
}
}
void loop(){
if(mills() - wifi_check >= 30000 || first_connect == 1){ //check every 30 sec if we are connected or if it's the initial connection check straight away
if(wifiMulti.run() != WL_CONNECTED) { //we are not connected
// print to screen every 1 sec
if(mills() - wifi_connection_counter >= 1000){
lcd.clear();
lcd.print(seconds++);
lcd.print(" ");
wifi_connection_counter = mills(); //reset the 1 sec timer
}
}else{ //we are connected
first_connect = 0;
}
wifi_check = mills(); //reset the 30 sec check
}
}
正如我所说,这是一个非常粗糙的未经测试的示例,但它避免了使用会阻塞的delay(),我怀疑如果wifiMulti需要类似“.run()”的东西,它也可能会阻止它正常工作。基本上,如果可以的话,避免使用delay()。
这样的东西也应该适用于常规 WiFi(),如果循环() 中的代码太多,您可以将其全部放在一个单独的函数中,然后从循环() 中调用该函数。
希望这有帮助