#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber= 2632350;
const char*myWriteAPIKey="0NSOZG90XD1QW0SA";
int statusCode;
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
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
}
void connectToCloud(){
if(WiFi.status() != WL_CONNECTED){
Serial.print("ATTEMPTING TO CONNECT");
while(WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid , pass);
Serial.print(".");
delay(500);
}
}
Serial.println("/nConnected");
}
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 (and the LED)
} else {
digitalWrite(relayPin, LOW); // Turn off the relay (and the LED)
}
delay(1500); // Wait for half a second before reading again
}
void writeData(){
ThingSpeak.setField(1,ldrValue);
ThingSpeak.setField(2,relayPin);
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode==200)
Serial.println("Channel Update Successful");
else
Serial.println("Problem Writing Data. HTTP error code :"+
String(statusCode));
delay((500));
}