I created an application to control and Arduino Uno R3 wirelessly using an Arduino Wifi shield. In developing it I noticed that when I set the WiFi shield in server mode, it stops listening after about 10 seconds of inactivity, or after 10 seconds without a client connected to it. Does anybody know if this is the case and how to change this timeout? I wrote a small sketch to illustrate the problem.
I added the code so it can be viewed instead of downloaded:
/*
Echo Server
A simple server that distributes that echoes what the client sends.
Circuit:
Arduino UNO R3 + Arduino WiFi shield attached
*/
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "MyNet"; // your network SSID (name)
char pass[] = "MyPassword"; // your network password (use for WPA, or use as key for WEP)
char buffer[100]; // Input buffer
int index = 0; // index for input buffer
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network.
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// start the server:
server.begin();
// connected now, print out the status:
printWifiStatus();
memset(buffer, '\0', sizeof(buffer));
index = 0;
}
void loop() {
// wait for a new client:
WiFiClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clean out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
client.flush();
alreadyConnected = true;
}
if (client.available() > 0) {
// read a byte incoming from the client:
char thisChar = client.read();
if ((thisChar != '\n')
&& (thisChar != '\r')
&& (index < sizeof(buffer))
) {
buffer[index++] = thisChar;
}
else {
client.println(buffer);
client.flush();
Serial.println(buffer);
memset(buffer, '\0', sizeof(buffer));
index = 0;
}
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}