#include <ESP32Servo.h>
// 180 deg horizontal MAX
Servo horizontal;
int servoh = 90;
const int servohLimitHigh = 180;
const int servohLimitLow = 0;
// 65 deg MAX
Servo vertical;
int servov = 45;
const int servovLimitHigh = 135;
const int servovLimitLow = 45;
// Define LDR pins
const int ldrtop = A0; // Top LDR
const int ldrbottom = A2; // Bottom LDR
const int ldrleft = A1; // Left LDR
const int ldrright = A3; // Right LDR
// Movement thresholds and timing
const int tol = 50; // Threshold for movement
const unsigned long moveDelay = 20; // Delay for servo movement
unsigned long lastMoveTime = 0; // Last movement time
void setup() {
// Attach servos to corresponding pins
horizontal.attach(9); // Horizontal servo connected to pin 9
vertical.attach(10); // Vertical servo connected to pin 10
// Set initial positions
horizontal.write(90);
vertical.write(45);
Serial.begin(9600); // Initialize Serial Monitor
delay(3000); // Initial delay for setup stabilization
}
void loop() {
// Read LDR values
int topVal = analogRead(ldrtop); // Top LDR
int bottomVal = analogRead(ldrbottom); // Bottom LDR
int leftVal = analogRead(ldrleft); // Left LDR
int rightVal = analogRead(ldrright); // Right LDR
unsigned long currentMillis = millis();
// Vertical Servo Movement (Up/Down)
if (topVal > bottomVal + tol) { // If top LDR detects more light
if (currentMillis - lastMoveTime >= moveDelay) {
servov = servov - 1;
if (servov < servovLimitLow) {
servov = servovLimitLow;
}
vertical.write(servov);
Serial.println("Moving Upward");
lastMoveTime = currentMillis;
}
} else if (bottomVal > topVal + tol) { // If bottom LDR detects more light
if (currentMillis - lastMoveTime >= moveDelay) {
servov = servov + 1;
if (servov > servovLimitHigh) {
servov = servovLimitHigh;
}
vertical.write(servov);
Serial.println("Moving Downward");
lastMoveTime = currentMillis;
}
}
// Horizontal Servo Movement (Left/Right)
if (leftVal > rightVal + tol) { // If left LDR detects more light
if (currentMillis - lastMoveTime >= moveDelay) {
servoh = servoh + 1;
if (servoh > servohLimitHigh) {
servoh = servohLimitHigh;
}
horizontal.write(servoh);
Serial.println("Moving Left");
lastMoveTime = currentMillis;
}
} else if (rightVal > leftVal + tol) { // If right LDR detects more light
if (currentMillis - lastMoveTime >= moveDelay) {
servoh = servoh - 1;
if (servoh < servohLimitLow) {
servoh = servohLimitLow;
}
horizontal.write(servoh);
Serial.println("Moving Right");
lastMoveTime = currentMillis;
}
}
delay(100); // Small delay between loops
}