The use of the ESP8266 in the world of IoT

User avatar
By SemirS
#54728 I was trying to find a solution for this problem for a long time.

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:

Code: Select allvoid 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))
User avatar
By SemirS
#55570 Anybody? Any suggestions?

Could the problem be the fact that I change the mode of the ESP multiple times before I set it up as AccesPoint and Station? I first use it as an Soft AccesPoint to get the SSID and password of the network (from another device), then I set it as Station to send the SSID and password to another ESP, and in the end I set it as AccesPoint and Station.

Or maybe it can be because of the Router? What I noticed was, when the updating of the ThingSpeak channel stops to work and I restart the router then the update works again, and later, after multiple updates it stops working again.

Any help would be appreciated.