0

In the following code, the Arduino is reconnecting to the WiFi after several loops. The idea is to check and re-establish WiFi connection every 30 minutes or so.

However, the WiFiServer seems to stop working after the reconnecting to the WiFi network. At least I get a timeout, if I try to request data by calling the Arduino's IP address.

#include <SPI.h>
#include <WiFi101.h>

// the IP address for the shield:
IPAddress ip(12,34,56,78);    

char ssid[] = "wifinetwork";   
char pass[] = "correcthorsebatterystaple";

int status = WL_IDLE_STATUS;
int count = 0;
int retries;

WiFiServer server(80);

void setup()
{  
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  connectToWiFi();

  server.begin();
  Serial.println("Server Started");
}

void loop () {
  count++;
  Serial.println(count);
  WiFiClient client = server.available();

  if(client) {
    Serial.print("Connected to a client : "); 

    if(client.connected()) {
        Serial.println("Response Sent to Client"); 
        client.println("Data"); 
    }  

    delay(5);
    client.stop();
    Serial.println("Client is disconnected");
  }

  if (count > 10) {
    Serial.println("Reconnect to WiFi");
    connectToWiFi();
    server.begin();
    count = 0;
  }

  delay(2000); // Wait for 2 seconds before starting to listen again 
}

void connectToWiFi(){
  WiFi.config(ip);
  retries = 0;

  // attempt to connect to Wifi network:
  do {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    retries++;
    delay(2000);
  } while(status != WL_CONNECTED && retries < 3);

  if (WiFi.status() == 3) {
    Serial.println("Connected");
  }
}
  • begin() it again – Juraj Jul 30 at 7:26
  • Already tried that, but unfortunately did not change anything. I edited the code above. – wheeler Jul 30 at 7:31
  • why do you reconnect? – Juraj Jul 30 at 8:15
  • I can't guarantee a stable/continuous WiFi connection. Hence, the Arduino shall search and reconnect to the WiFi network every few minutes, because it may lost connection. – wheeler Jul 30 at 8:23
  • you could try to reinitialize the server object with server = WiFiServer(80) and then begin() it. (the assignment copies the content of the temporary object into the existing instance.) – Juraj Jul 30 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.