I use Thingspeak without its library, with following code. The code is working for years but I recently found out there are a few things that need correction.
- is a delay needed after client.stop() ? How much ?
- is it advisable (or not) to use client.flush() before client.stop() ?
- is the use of \r and \n correct in my code ?
- should I use
client.print(postStr.length());orclient.print(String(postStr.length()));?
My code:
if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com
{
String postStr = apiKey;
postStr += "&field1=";
postStr += String(valveState);
postStr += "&field2=";
postStr += String(hiLvlState);
postStr += "&field3=";
postStr += String(loLvlState);
postStr += "&field4=";
postStr += String(valveDelayedClosureExecution);
postStr += "&field5=";
postStr += String(alarmState);
postStr += "&field6=";
postStr += String(get3231Temp());
postStr += "&field7=";
postStr += String(valveOpenTime);
postStr += "&field8=";
postStr += String(waterUsage);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
// client.print(String(postStr.length()));
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.println(F("Thingspeak executed"));
delay(4000);
}
client.flush();
client.stop();
delay(5):