I wrote an example to prove the issue.
1. Start CMD on windows machine and issue ping 192.168.4.1 -t
2. Change "your-ssid" and "your-password" to reflect your network.... then Run the sketch
3. find "myhost" in your wireless AP settings on the PC and log in.... (do it quickly you have 20 seconds)
4. you will see ping working
5. in 20 seconds the code will attempt to log onto an AP that does not exist....
6. the ping will start failing.....
WHY?
RichardS
Code: Select all#include <WiFi.h>
void setup() {
Serial.begin(500000);
}
char *hostName = "myhost";
char *hostPassword = "";
char *ssid = "your-ssid";
char *password = "your-password";
static char *oldssid = ssid;
int connected = 0;
void refresh(bool firstTime) {
static bool Connected = false;
static bool tryAgain = false;
static int cnt = 0;
connected = WiFi.status() == WL_CONNECTED || WiFi.isConnected();
// runs this only once
if (firstTime) {
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(hostName, hostPassword, 10);
Serial.printf("setting %s with %s\n", hostName, hostPassword);
connected = false;
tryAgain = true;
}
// if the ssid changed then reconnect
if (ssid != oldssid) {
oldssid = ssid;
tryAgain = true;
}
// this runs when we change something
if (tryAgain) {
tryAgain = false;
connected = false;
cnt = 0;
if (ssid != "" && password == "") {
Serial.printf("Connecting to %s without password\n", ssid);
WiFi.disconnect();
WiFi.begin(ssid);
}
else if (ssid != "" && password != "") {
Serial.printf("Connecting to %s with password\n", ssid);
WiFi.disconnect();
WiFi.begin(ssid, password);
}
else {
Serial.printf("WIFI", "huh??\n");
WiFi.disconnect();
WiFi.begin();
}
}
}
void loop() {
refresh(true); // runs once
for (;;) {
if (millis() / 1000 == 20) { // change the ssid in 20 seconds
ssid = "tmp";
}
if (millis() % 500 == 0) { // show progress
Serial.printf("%u connected = %u\n", millis() / 1000, connected);
delay(10);
}
refresh(false);
}
}