#include <Servo.h>
// Define the pin numbers for LDR sensors and servo motor
const int ldr1Pin = 2; // Connect LDR1 to digital pin 2
const int ldr2Pin = 3; // Connect LDR2 to digital pin 3
const int servoPin = 9; // Connect servo motor to digital pin 9
Servo myServo;
void setup() {
// Attach servo to the servo pin
myServo.attach(servoPin);
// Set LDR pins as inputs
pinMode(ldr1Pin, INPUT);
pinMode(ldr2Pin, INPUT);
}
void loop() {
// Read the values from LDR sensors
int ldr1Value = digitalRead(ldr1Pin);
int ldr2Value = digitalRead(ldr2Pin);
// For up train
if (ldr1Value == LOW && ldr2Value == HIGH) {
rotateServo(90); // Rotate servo to 90 degrees
while (digitalRead(ldr2Pin) == HIGH) {
// Wait until 2nd LDR gives low value
// This loop ensures that the servo remains in position until the condition is met
}
} else if (ldr1Value == HIGH && ldr2Value == LOW) {
rotateServo(0); // Rotate servo to 0 degrees
while (digitalRead(ldr1Pin) == HIGH) {
// Wait until 1st LDR gives low value
// This loop ensures that the servo remains in position until the condition is met
}
}
// For down train
if (ldr2Value == LOW && ldr1Value == HIGH) {
rotateServo(90); // Rotate servo to 90 degrees
while (digitalRead(ldr1Pin) == HIGH) {
// Wait until 1st LDR gives low value
// This loop ensures that the servo remains in position until the condition is met
}
} else if (ldr2Value == HIGH && ldr1Value == LOW) {
rotateServo(0); // Rotate servo to 0 degrees
while (digitalRead(ldr2Pin) == HIGH) {
// Wait until 2nd LDR gives low value
// This loop ensures that the servo remains in position until the condition is met
}
}
}
void rotateServo(int angle) {
// Rotate the servo to the specified angle
myServo.write(angle);
// Wait for the servo to reach the desired position
delay(1000); // Adjust this delay as needed
}