Connect to wifi during setup or loop?

I've got some copied code that's been running for a couple of years.
This connects to the wifi in the void setup() part of the code.

Then in the void loop() it regularly sends data to Thingspeak.

This has run remarkably reliably for a couple of years, however if the instruction to connect to the wifi is in the void setup() not the loop, then surely there is nothing to instruct it to reconnect to the wifi in the loop, if the connection is dropped ?
I'm not entirely understanding why it remains connected so reliably :slightly_smiling_face:.

Is the Arduino ever reset ?
How is it powered ?

Because the engineers that designed it understood that users would need that.

There is a 'connected()' method that will tell you if you have a connection or not. You can poll it and reconnect if the answer is no.

On a periodic basis my code that uses WiFi will check for WiFi is still connected and if not connected, reconnect.

I have found the below WiFi connection check to be reliable.

//check for a is-connected and if the WiFi 'thinks' its connected, found checking on both is more reliable than just a single check
if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )

It's a sad reflection on our times that someone would wonder why something works reliably... my question is usually why it doesn't.

I have 3 ESP8266s connected to Thingspeak.

Since I have past experience of horribly unreliable Raspberry Pi set ups, I have one of the ESP8266s with a plug in timer which power cycles it twice a day. So I understand why that one is reliable.

The other two are permanently powered. Except for power cuts and the like, which are very infrequent.
If my wifi connection is before the main loop, once it drops the connection, should I expect it to remain dropped ? That is my starting assumption. In which case, it's remarkably reliable.

I'm wondering if I should modify the code.

Once an ESP8266 has been fed the credentials of your WLAN, as happens the first time the device is switched on and setup() is invoked, then it caches these in flash memory. If the connection is subsequently broken, say your router power cycles, the ESP8266 attempts to restore the connection automatically based on the cached credentials.

1 Like

Well, I have a number of wifi connected ESP8266 and ESP32 devices that have been running 24/7 for many months without any reboot. If you have to do that, you are doing something wrong.

But if your application could do irrational things if not connected, you should of course monitor the connection.

I don't HAVE to reboot the ESP8266, but having come from using less reliable Raspberry Pis, I decided to put a timer on one of the 3 ESP8266s. The other 2 show that this probably isn't necessary.

6v6gt has explained why it is working OK.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.