#include <WiFi.h> // For ESP32. If using Arduino with WiFi shield, use <WiFi101.h> or appropriate WiFi library.
#include <WiFiClient.h> // Use WiFiClient for HTTP requests.
#define LDR_PIN A0 // For Arduino, A0 is used for analog input
#define LED_PIN 13 // Common digital pin for LED
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace these with your ThingSpeak credentials
const char* thingSpeakServer = "http://api.thingspeak.com/update";
const char* writeAPIKey = "39SNENCWNDY86C1Z";
int a;
void setup() {
Serial.begin(9600);
// Initialize pins
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
}
void loop() {
int ldrValue = 0;
// Average multiple readings for better stability
for (int i = 0; i < 10; i++) {
ldrValue += analogRead(LDR_PIN);
delay(10); // Small delay between readings
}
ldrValue /= 10; // Average the readings
if (ldrValue > 1121) { // Low light
digitalWrite(LED_PIN, HIGH);
a = HIGH;
} else if (ldrValue < 1120) { // High light
digitalWrite(LED_PIN, LOW);
a = LOW;
}
sendDataToThingSpeak(ldrValue, a);
Serial.println("LDR Value:");
Serial.println(ldrValue);
Serial.println("LED State:");
Serial.println(a);
delay(5000); // Delay before next reading
}
void sendDataToThingSpeak(int lux, int a) {
if (WiFi.status() == WL_CONNECTED) {
WiFiClient client;
String url = "/update?api_key=" + String(writeAPIKey) + "&field1=" + String(lux) + "&field2=" + String(a);
if (client.connect(thingSpeakServer, 80)) { // Connect to ThingSpeak server on port 80
client.println("GET " + url + " HTTP/1.1");
client.println("Host: " + String(thingSpeakServer));
client.println("Connection: close");
client.println();
// Wait for response from server
while (client.connected() || client.available()) {
if (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
client.stop(); // Close connection
} else {
Serial.println("Connection to ThingSpeak failed");
}
} else {
Serial.println("Error: Not connected to WiFi");
}
}