I bought today a new NodeMCU and at first, it was working fine and communicating well with the thingspeak server and sending data from my photoresistor sensor, but after a 20-30 mins, it won't communicate with the api.thingspeak.com and prompt a "connection failed" message.
I've tried using the ThingSpeak example for a single writefield but I am prompted with an error -301 which also meant that the communication to the thingspeak server has failed.
I've also tried changing the host with the added https://, still no luck.
This is the code that I am using:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid = "jmySSID";
const char* password = "myPass";
const char* host = "api.thingspeak.com";
const char* APIKey = "myAPI";
void setup()
{
Serial.begin(9600);
delay(10);
//WiFi.mode(WIFI_STA);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop()
{
delay(5000);
value = analogRead(A0);
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/update";
url += "?api_key=";
url += APIKey;
url += "&field1=";
url += value;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
Here is the error message: