#include <WiFi.h>
#include "ThingSpeak.h"
// Wi-Fi credentials
char ssid[] = "Wokwi-GUEST"; // SSID for the Wi-Fi network
char pass[] = ""; // Password for the Wi-Fi network (empty)
// ThingSpeak channel details
unsigned long myChannelNumber = 2629998;
const char *myWriteAPIKey = "WCAJRI5PH2NAZ8LX";
const char *server = "api.thingspeak.com";
// Pin definitions
const int ldrPin = 34; // ADC pin for LDR
const int relayPin = 23; // Digital pin for relay control
int ldrValue = 0; // Variable to store the LDR value
int threshold = 500; // Threshold value for LDR to activate the relay
WiFiClient client;
void setup() {
Serial.begin(115200); // Start serial communication for debugging
pinMode(ldrPin, INPUT); // Set the LDR pin as input
pinMode(relayPin, OUTPUT); // Set the relay pin as output
digitalWrite(relayPin, LOW); // Ensure relay is off initially
// Connect to Wi-Fi
WiFi.begin(ssid, pass);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
ldrValue = analogRead(ldrPin); // Read the LDR value
Serial.print("LDR Value: ");
Serial.println(ldrValue); // Print the LDR value to the serial monitor
// Check if the LDR value is below the threshold
if (ldrValue < threshold) {
digitalWrite(relayPin, HIGH); // Turn on the relay
} else {
digitalWrite(relayPin, LOW); // Turn off the relay
}
// Update ThingSpeak with the LDR value
ThingSpeak.setField(1, ldrValue);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Channel update successful.");
} else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
delay(5000); // Wait for 5 seconds before the next update
}