I am trying to read the field data I saved in my channel, of course, I made the channel public.
I am using Arduino Uno and ESP-01 as a WiFi module.
I can logged the data successfully
but I cannot read the last data I logged.
I can read the data using web browser but cannot with Arduino.
https://api.thingspeak.com/channels/948343/fields/1/last.txt
I also tried the ThingSpeak library but to fail.
I googled and tried to change wireless network but to fail either.
Here is my sketch.
I cannot read anything.
The server returns nothing.
I missed something?
#include <WiFiEsp.h>
#include <SoftwareSerial.h>
#define READ_INTERVAL 20000L // reading interval
SoftwareSerial ESPSerial(2, 3); // port for ESP-01
WiFiEspClient client;
char AP[] = "my SSID";
char PW[] = "SSID PW";
char HOST[] = "api.thingspeak.com";
unsigned long time_previous, time_current;
void setup() {
Serial.begin(9600); // UART to computer
ESPSerial.begin(9600); // UART to ESP-01
WiFi.init(&ESPSerial); // initialize ESP-01
Serial.println(F("* Try to connect to AP"));
if (WiFi.begin(AP, PW) != WL_CONNECTED) {
Serial.println(F("* Cannot connect to AP"));
while (1);
}
else {
Serial.println(F("* Connected to AP."));
}
Serial.println();
time_previous = millis();
}
void loop() {
time_current = millis();
if (time_current - time_previous >= READ_INTERVAL) {
time_previous = time_current;
readTempData(); // read last logged temperature data
}
}
void readTempData() {
if (!client.connect(HOST, 80)) { // make a TCP connection
Serial.println(F("* Connection error to ThingSpeak server"));
Serial.println();
time_previous = millis();
cleanUpTCPconnection(); // clean up TCP connection
}
else { // read temperature data
Serial.println(F("* Try to read the last logged temperature data"));
String command = "GET ";
String url = "/channels/948343/fields/1/last.txt";
String readStr = command + url;
client.println(readStr);
client.println();
// server response
unsigned long time_start_wait = millis(), wait_time = 20000;
Serial.println();
Serial.print("\"");
while (millis() < time_start_wait + wait_time) {
while (client.available()) {
Serial.print(client.read());
}
}
Serial.println("\"");
cleanUpTCPconnection(); // clean up TCP connection
}
}
void cleanUpTCPconnection() {
if (client.connected()) {
client.flush();
client.stop();
}
}