const int ledPin = D1; // NodeMCU D1 pin (GPIO 5) or any digital pin
const int ldrPin = A0; // NodeMCU A0 pin or appropriate ESP32 analog pin
// Adjust the threshold value as needed for your environment
int threshold = 500;
void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(ldrPin, INPUT); // Set LDR pin as input
}
void loop() {
int ldrValue = analogRead(ldrPin); // Read the value from the LDR
Serial.print("LDR Value: ");
Serial.println(ldrValue); // Print the LDR value to the Serial Monitor
// If the light level is below the threshold, turn on the LED (it's dark)
if (ldrValue < threshold) {
digitalWrite(ledPin, HIGH);
Serial.println("-> DARK, LED is ON");
} else {
// If the light level is above the threshold, turn off the LED
digitalWrite(ledPin, LOW);
Serial.println("-> LIGHT, LED is OFF");
}
delay(500); // Small delay for stability
}