#include <WiFi.h>
#include <ThingSpeak.h>
#define LDR_PIN 34
#define LED_PIN 5
char ssid[] = "Wokwi-GUEST"; // WiFi SSID
char pass[] = ""; // WiFi Password
WiFiClient client;
unsigned long myChannelNumber = 2640574; // Your ThingSpeak channel number
const char* myWriteAPIKey = "EC7NOMX3TYQDCRU2"; // ThingSpeak Write API Key
bool ledstate = false; // Boolean variable to track LED state
int statusCode;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void getWiFi() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
Serial.print(".");
delay(5000);
}
}
Serial.println("\nConnected");
}
void loop() {
getWiFi(); // Ensure WiFi is connected
int ldrValue = analogRead(LDR_PIN); // Read the LDR value
Serial.println(ldrValue); // Print LDR value to the Serial Monitor
int threshold = 2000; // Set the light threshold
if (ldrValue < threshold) {
digitalWrite(LED_PIN, HIGH); // Turn on LED if it's dark
ledstate = true; // Update LED state
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED if it's bright
ledstate = false; // Update LED state
}
// Update ThingSpeak with the current LED state
ThingSpeak.setField(1, ledstate ? 1 : 0);
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (statusCode == 200) {
Serial.println("Channel Updated");
} else {
Serial.println("Problem Updating Channel: HTTP Error Code " + String(statusCode));
}
delay(5000); // Delay for stability and to prevent rapid updates to ThingSpeak
}