#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define WIFI_SSID "Wokwi-GUEST" // Replace with your Wi-Fi SSID
#define WIFI_PASSWORD "" // Replace with your Wi-Fi password
#define API_URL "https://api.thingspeak.com/channels/1921629/fields/1.json?results=1"
#define LED_PIN 4 // GPIO pin for LED
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWi-Fi Connected!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(API_URL);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("API Response: " + response);
// Parse JSON
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, response);
if (!error) {
const char* field1Value = doc["feeds"][0]["field1"]; // Extract "field1"
Serial.print("Field1 Value: ");
Serial.println(field1Value);
// Control LED
if (String(field1Value) == "0") {
digitalWrite(LED_PIN, LOW);
Serial.println("LED OFF");
} else {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED ON");
}
} else {
Serial.println("JSON Parsing Failed!");
}
} else {
Serial.print("HTTP Request Failed! Error Code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Wi-Fi Disconnected!");
}
delay(10000); // Wait few seconds before the next request
}