I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:
uploadData() {
String apiKey = "ESDS8678890SDDS";
String myData = "45.5"; // example of data to send
if (espClient.connect(server,80)) {
String postStr = apiKey;
postStr +="&field1=";
postStr += String(myData);
postStr += "\r\n\r\n";
espClient.print("POST /update HTTP/1.1\n");
espClient.print("Host: api.thingspeak.com\n");
espClient.print("Connection: close\n");
espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
espClient.print("Content-Type: application/x-www-form-urlencoded\n");
espClient.print("Content-Length: ");
espClient.print(postStr.length());
espClient.print("\n\n");
espClient.print(postStr);
Serial.print(postStr);
Serial.print("My Data: ");
Serial.print(myData);
Serial.print("\n");
}
espClient.stop();
}
But I have no idea how to retrieve data from ThingSpeak using ESP8266.
// Using XXXXX here as my channel is private
GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2
I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.
Help would be appreciated.
Thanks.
1 Answer 1
Connect to the server as usual with espClient.connect()
. The following request should return a JSON object containing your channel description and the first 2 entries in your feed:
espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");
espClient.println();
If it's a private channel, then you must supply your Read API key like this:
espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");
Notice that I use println()
and not print()
in order to implicitly terminate each request line properly. You should end each line not with \n
but with \r\n
. You only need to type this yourself if you use print()
.
To read the returned JSON data:
while (espClient.available() == 0); // wait till something comes in; you may want to add a timeout here
unsigned long lastRead = millis(); // keeps track of last time a byte was read
while (millis() - lastRead < 2000) { // while 2 secs havent passed since a byte was read
while (espClient.available()) {
Serial.print(espClient.read());
lastRead = millis(); // update last time something was read
}
}
client.stop(); // close socket
To parse the JSON string, you either get a library from GitHub or you parse the string yourself.