I have implemented an ESP8266WebServer which works flawlesly (and very fast). I also added a function to send data to ThingSpeak every minute. The code i used for sending data worked before but coupled with the WebServer showed some isues. The wierd thing is that the code for sending data sometimes worked for hours but sometimes works for just 5-6 minutes (5-6 posts) and after that i always get client.connect(host, 80) == false.
The function for sending data to ThingSpeak:
void updateThingSpeak() {
//Serial.println("Update ThingSpeak-a!");
const char *host = "184.106.153.149";
WiFiClient client;
if (!client.connect(host, 80)) {
//Serial.println("Connection to ThingSpeak failed!");
client.stop();
} else {
int light, smoke;
digitalWrite(SMOKE_PIN, LOW);
digitalWrite(LIGHT_PIN, HIGH);
delay(5);
light = analogRead(A0);
digitalWrite(LIGHT_PIN, LOW);
digitalWrite(SMOKE_PIN, HIGH);
delay(5);
smoke = analogRead(A0);
digitalWrite(SMOKE_PIN, LOW);
//Definisemo URI za request koji saljemo
String url = "/update?api_key=" + writeApiKey + "&field1=" + String(smoke) + "&field2=" + String(light) + "&field3=" + String(motionValue) + "&field4=" + dht.readTemperature() + "&field5=" + dht.readHumidity() + "&field6=" + WiFi.RSSI();
//Saljemo request na server(ThingSpeak)
client.print(String("POST ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
motionValue = 0;
//client.stop();
}
}
I made many changes to this code while trying to find a solution, but my current code is the above.
Should i use client.flush()? Do i even need client.stop() cause the client is local?
Notes:
- the Ports for the WebServer and client for sending are not the same, for WebServer i use 81 and for client (sending data) 80
- the IP is static (Wifi.config(ip, gateway, subnet))
- the ESP is in accesPoint and Station mode at the sam time (WiFi.mode(WIFI_AP_STA))