Hi there dear people!
I am trying to connect ThingSpeak and send data there with my arduino R3 and arduino R3 wifi shield. The problem is that arduino always needs at least two tries to connect to the server. First try I always get the error message "Connection FAILED" (client.connect(thingSpeakAddress, 80)!=1). For my project I need the connection to succeed on first try. Does anyone have any ideas? It might also be some simple thing I haven't noticed since I have struggled with this quite a while.
#include <SPI.h>
#include <WiFi.h>
WiFiClient client;
char thingSpeakAddress[] = "184.106.153.149";
char writeAPIKey[17] = "xxxxxxxxxxxxxxxx"; //your thingspeak apikey
boolean lastConnected = false;
int failedCounter = 0;
void setup() {
Serial.begin(9600);
delay(1000);
pinMode(4, OUTPUT);
digitalWrite(4, HIGH); // SD chipselect not active
WiFiOn();
POST();
}
void loop() {
}
void WiFiOn(){
int status = WL_IDLE_STATUS;
if(WiFi.status() == WL_NO_SHIELD){
Serial.println(F("WiFi shield not present"));
}
char ssid[] = "xxxxxxxxxxxxxx"; //your ssid
Serial.print(F("Attempting to connect to open SSID: "));
Serial.println(ssid);
status = WiFi.begin(ssid);
delay(10000);
if(status == WL_CONNECTED){
Serial.println(F("You're connected to the network\n"));
IPAddress ip = WiFi.localIP();
Serial.print(F("IP Address: "));
Serial.println(ip);
}
}
void POST(){
while(true){
float timenow = millis();
int rssi = WiFi.RSSI();
int noCharCount = 0;
//empty the buffer
while(client.connected()){
while(client.available()){
char inChar = client.read();
Serial.write(inChar);
noCharCount = 0;
}
noCharCount++;
//if no data is received in 10s then abort.
if(noCharCount > 10000)
{
Serial.println();
Serial.println(F("Timeout"));
client.stop();
}
delay(1);
}
if (!client.connected() && lastConnected){
client.flush();
client.stop();
Serial.println(F("...disconnecting"));
Serial.print(F("connection time: "));
Serial.println((millis() - timenow)/1000);
break;
}
if (failedCounter > 3) { //Disconnect if third connection won't work
client.flush();
client.stop();
Serial.println(F("...Disconnecting"));
break;
}
if(!client.connected()){
updateThingSpeak("field1="+String(rssi)+"&field2="+(failedCounter));
}
lastConnected = client.connected();
}
}
void updateThingSpeak(String tsData){
if (client.connect(thingSpeakAddress, 80)==1)
{
Serial.println(F("Connected to server"));
char outbuf[90];
strcpy(outbuf, "POST /update HTTP/1.1\r\nHost: api.thingspeak.com\r\nConnection: close\r\n");
client.print(outbuf);
sprintf(outbuf, "X-THINGSPEAKAPIKEY: %s\r\n", writeAPIKey);
client.print(outbuf);
sprintf(outbuf, "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: %u\r\n\n", tsData.length());
client.print(outbuf);
client.println(tsData);
if(client.connected()){
Serial.println(F("POST request was sent!\n"));
failedCounter = 0;
}
else{
Serial.println(F("Connection failed"));
failedCounter++;
}
}
else{
Serial.println(F("Connection FAILED"));
failedCounter++;
}
}