#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String payload;
const char* server = "http://api.thingspeak.com/channels/1914850/feeds/last.json?api_key=TSI9NTNCKA8Z8FSR";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("OK! IP=");
Serial.println(WiFi.localIP());
Serial.print("Fetching ");
Serial.print(server);
}
void loop() {
WiFiClient client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
if (http.begin(client, server)) { // HTTP
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpResponseCode = http.GET();
// httpCode will be negative on error
if (httpResponseCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpResponseCode);
// file found at server
if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = http.getString();
Serial.println(payload);
StaticJsonDocument<1024> doc;
DeserializationError error =deserializeJson(doc,payload);
if (error) {
Serial.print("deserializeJson() failed");
Serial.println(error.c_str());
return;
}
Serial.println("........................................................");
const char* parsedPayload0 = doc["created_at"];
Serial.print("created_at=");
Serial.println(parsedPayload0);
float parsedPayload1 = doc["field1"];
Serial.print("Temperature=");
Serial.println(parsedPayload1);
float parsedPayload2 = doc["field2"];
Serial.print("Humidity=");
Serial.println(parsedPayload2);
Serial.println("........................................................");
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
} else {
Serial.printf("[HTTP} Unable to connect\n");
}
delay(2000);
}