Unable to execute reliable WiFi scanning

I was also struggling with this topic like Mark81 after building from sample code found on the web. I was experiencing the same issues.

I think the root of the problem is actually the number of scans being started. I think there are too many!

The reason for too many scans is the way the WIFI_SCAN_FAILED status code is being interpreted. Like Mark81's, the example I was working from began a new scan when a WIFI_SCAN_FAILED code was returned by WiFi.scanComplete() .

WIFI_SCAN_FAILED is defined with value -2. It's real meaning however is not clear and I found this documentation relating to the ESP8266:

IDE example — ESP8266 Arduino Core 3.1.2-21-ga348833 documentation (arduino-esp8266.readthedocs.io)

The important point is that in that documentation the -2 code does not mean the scan has completed , far from it, with reference to WiFi.scanComplete() it says "If scanning has not been triggered yet, it would return -2."

Combining this knowledge with the example I was working from I realised starting another scan when getting a -2 is not the correct action to take; unless you have reason to believe the scan will never start.

kenb4's solution comes at it from a slightly different angle but achieves the same. My explanation I hope clarifies why kenb4's solution works and helps answering Mark81's post #8.