#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// ---------------- WiFi Configuration ----------------
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ---------------- ThingSpeak Configuration ----------------
const char* readAPIKey = "ZI3B01IH4EO2DJGE"; // Replace with your read key
const char* channelID = "3110288"; // Replace with your channel ID
// ---------------- Control Variables ----------------
String lastEntryID = "";
unsigned long lastFetchTime = 0;
const long fetchInterval = 5000; // Check every 5 seconds
void setup() {
Serial.begin(115200);
Serial.println("ESP32 ThingSpeak Receiver (Auto Fetch)");
Serial.println("--------------------------------------");
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n✅ WiFi Connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastFetchTime >= fetchInterval) {
lastFetchTime = currentTime;
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "https://api.thingspeak.com/channels/" + String(channelID) +
"/feeds.json?api_key=" + String(readAPIKey) + "&results=1";
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
// Parse JSON
const size_t capacity = 8 * 1024; // Allocate enough memory
DynamicJsonDocument doc(capacity);
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
JsonArray feeds = doc["feeds"];
if (feeds.size() > 0) {
JsonObject feed = feeds[0];
String entryID = feed["entry_id"].as<String>();
if (entryID != lastEntryID) {
lastEntryID = entryID;
String device_id = feed["field1"].as<String>();
String start_lat = feed["field2"].as<String>();
String start_lon = feed["field3"].as<String>();
String total_distance_km = feed["field4"].as<String>();
String timestamp = feed["field5"].as<String>();
Serial.println("\n--------------------------------------");
Serial.println("Receiving...");
Serial.println("Payload Received:");
Serial.println(device_id + " | " + total_distance_km + " km");
Serial.println(start_lat + " | " + start_lon);
Serial.println(timestamp);
Serial.println("--------------------------------------\n");
}
} else {
Serial.println("⚠️ No feeds available.");
}
} else {
Serial.println("❌ JSON Parse Error");
}
} else {
Serial.println("❌ HTTP Error: " + String(httpCode));
}
http.end();
} else {
Serial.println("⚠️ WiFi disconnected. Retrying...");
}
}
}