// Include the Servo library for servo motor control
#include <Servo.h>
// Define the analog pin connected to the LDR module's analog output
const int LDR_PIN = A0;
// Define the digital PWM pin connected to the servo motor's signal wire
const int SERVO_PIN = 9;
// Create a Servo object
Servo myServo;
// Define a threshold value for light detection.
// Values below this are considered "dark", values above are "light".
// You might need to adjust this value based on your LDR module
// and the light conditions in your environment.
// You can monitor LDR values using the Serial Monitor to find a suitable threshold.
const int LDR_THRESHOLD = 500; // Example value, typically between 0 and 1023
// Variable to store the current servo position (0 or 180 degrees)
int currentServoPos = 0; // Initialize to 0 degrees (light state)
void setup() {
// Attach the servo object to the specified servo pin
myServo.attach(SERVO_PIN);
// Initialize serial communication for debugging and monitoring LDR values
Serial.begin(9600);
// Set initial servo position to 0 degrees (assuming light at startup)
myServo.write(currentServoPos);
Serial.print("Initial servo position: ");
Serial.println(currentServoPos);
}
void loop() {
// Read the analog value from the LDR pin (0-1023)
int ldrValue = analogRead(LDR_PIN);
// Print the LDR value to the Serial Monitor for debugging
Serial.print("LDR Value: ");
Serial.println(ldrValue);
// Check if the LDR value indicates light
if (ldrValue > LDR_THRESHOLD) {
// If it's light, and the servo is not already at 0 degrees, move it
if (currentServoPos != 0) {
myServo.write(0); // Rotate servo to 0 degrees
currentServoPos = 0;
Serial.println("Light detected: Servo rotating to 0 degrees.");
}
} else { // The LDR value indicates darkness
// If it's dark, and the servo is not already at 180 degrees, move it
if (currentServoPos != 180) {
myServo.write(180); // Rotate servo to 180 degrees
currentServoPos = 180;
Serial.println("Dark detected: Servo rotating to 180 degrees.");
}
}
// Small delay to prevent rapid flickering and allow servo to reach position
// Adjust this delay as needed. A smaller delay means faster response but might
// lead to jitter if the LDR reading is unstable near the threshold.
delay(100);
}