#include <Servo.h>
// Pin Definitions
const int ldr1Pin = A0; // LDR 1 connected to A0
const int ldr2Pin = A1; // LDR 2 connected to A1
const int ldr3Pin = A2; // LDR 3 connected to A2
const int servoPin = 9; // Servo motor connected to digital pin 9
const int relayPin = 7; // Relay module connected to digital pin 7
Servo myServo;
void setup() {
pinMode(ldr1Pin, INPUT);
pinMode(ldr2Pin, INPUT);
pinMode(ldr3Pin, INPUT);
pinMode(relayPin, OUTPUT);
myServo.attach(servoPin);
Serial.begin(9600);
}
void loop() {
int ldr1Value = analogRead(ldr1Pin); // Read value from LDR 1
int ldr2Value = analogRead(ldr2Pin); // Read value from LDR 2
int ldr3Value = analogRead(ldr3Pin); // Read value from LDR 3
// Initialize the relay to OFF position as a default for each loop iteration
digitalWrite(relayPin, LOW);
if (ldr1Value > ldr2Value && ldr1Value > ldr3Value) {
myServo.write(0); // Move servo to 0 degrees
digitalWrite(relayPin, HIGH); // Turn ON the relay
Serial.println("LDR 1 is detected turn left.");
} else if (ldr2Value > ldr1Value && ldr2Value > ldr3Value) {
myServo.write(90); // Move servo to 90 degrees
digitalWrite(relayPin, HIGH); // Turn ON the relay
Serial.println("LDR 2 is detected turn straight.");
} else if (ldr3Value > ldr1Value && ldr3Value > ldr2Value) {
myServo.write(180); // Move servo to 180 degrees
digitalWrite(relayPin, HIGH); // Turn ON the relay
Serial.println("LDR 3 is detected turn right.");
} else {
}
delay(1000); // Delay a second before the next loop iteration
}