bool repeat = true;
bool scan_repeat = true;
int input;
int i = 0;
#include <WiFi.h>
void setup() {
Serial.begin(115200);
Serial.println(" ");
Serial.println("Saggita B* Initiatializd");
delay(1000);
Serial.println("Scan Networks (1) / Shut Down (0)");
Serial.flush();
while(Serial.available() == 0) {}
input = Serial.parseInt();
}
void loop() {
if(repeat == true and input == 1) {
Serial.println("Starting scan");
scan();
delay(2000);
}
else if(repeat == true and input == 0)
{
Serial.println("Shutting Saggita Down");
}
repeat = false;
}
int scan() {
WiFi.disconnect();
delay(500);
WiFi.mode(WIFI_STA);
delay(500);
int networks = WiFi.scanNetworks();
if (networks == 0 and scan_repeat == true) {
Serial.print("Networks not Found!");
}
else if(networks > 0 and scan_repeat == true) {
Serial.println("Networks Found");
delay(1000);
while(i <= networks){
Serial.println(WiFi.SSID(i));
i++;
delay(1000);
}
}
}
See the above code, the main problem with this code is whenever I enter '1' on my serial monitor, it completes the scan but the "while loop" which was used for the scan never ends, after printing out all the SSIDs, the loop seems to continue printing nothing at all. I tried almost everything, I tried to break the loop, and I tried to make the looping condition false too, but unfortunately nothing really adds up to its solution.
In setup, the serial port is started so text can be sent and printed, and WiFi is put in station mode so network scanning is allowed.
The loop function runs continuously and reads one byte from the serial buffer each time it executes.
Serial.read returns the value of the received byte, or -1 when no data is available, so the comparison only succeeds when the character ‘1’ is actually received.
When ‘1’ is received, the scan function is called.
The scan function asks the WiFi hardware to scan for nearby networks and returns the number found.
If no networks are found, a message is printed.
If networks are found, their SSID names are printed one by one thanks to the for loop.
It works because Serial.read is non-blocking and safe to call repeatedly, and WiFi.scanNetworks performs a scan each time it is called.
I did not put the unnecessary compound statements (the things within {}) when there was only one statement in the code flow but may be for better understanding you should use
#include <WiFi.h>
void scan() {
int n = WiFi.scanNetworks();
if (n == 0) {
Serial.println("No networks found");
} else {
for (int i = 0; i < n; i++) {
Serial.println(WiFi.SSID(i));
}
}
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
}
void loop() {
if (Serial.read() == '1') {
scan();
}
}
@sk1607 Also note, in your code, you call
Serial.println(WiFi.SSID(i));
with i with values from 1 to the number of networks found; whereas in @J-M-L 's code, the same function is called
Serial.println(WiFi.SSID(i));
with i ranging from 0...n-1; there's a big difference, if you think about it. Odds are good, somewhere under the hood an array is being indexed...