#include <ESP32Servo.h>
//horizontal bottom 180 , vertical top 45
// 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 (ESP32 uses different pin numbering)
const int ldrtopr = 34; // Top right LDR
const int ldrtopl = 35; // Top left LDR
const int ldrbotr = 32; // Bottom right LDR
const int ldrbotl = 33; // Bottom left 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(13); // Horizontal servo connected to GPIO 13
vertical.attach(12); // Vertical servo connected to GPIO 12
// Set initial positions
horizontal.write(90);
vertical.write(45);
Serial.begin(115200); // ESP32 typically uses 115200 baud rate for Serial Monitor
delay(3000); // Initial delay for setup stabilization
}
void loop() {
// Read LDR values
int lt = analogRead(ldrtopl); // Top left
int rt = analogRead(ldrtopr); // Top right
int ld = analogRead(ldrbotl); // Bottom left
int rd = analogRead(ldrbotr); // Bottom right
// Calculate average LDR values
int avt = (lt + rt) / 2; // Average value top
int avd = (ld + rd) / 2; // Average value down
int avl = (lt + ld) / 2; // Average value left
int avr = (rt + rd) / 2; // Average value right
int dvert = avt - avd;
int dhoriz = avl - avr;
unsigned long currentMillis = millis();
// Vertical Servo Movement
if (abs(dvert) > tol) {
if (avt < avd) {
if (currentMillis - lastMoveTime >= moveDelay) {
servov = servov - 1;
if (servov < servovLimitLow) {
servov = servovLimitLow;
}
vertical.write(servov);
Serial.println("Moving Downward");
lastMoveTime = currentMillis;
}
} else if (avt > avd) {
if (currentMillis - lastMoveTime >= moveDelay) {
servov = servov + 1;
if (servov > servovLimitHigh) {
servov = servovLimitHigh;
}
vertical.write(servov);
Serial.println("Moving Upward");
lastMoveTime = currentMillis;
}
}
}
// Horizontal Servo Movement
if (abs(dhoriz) > tol) {
if (avl > avr) {
if (currentMillis - lastMoveTime >= moveDelay) {
servoh = servoh - 1;
if (servoh < servohLimitLow) {
servoh = servohLimitLow;
}
horizontal.write(servoh);
Serial.println("Rotating Left");
lastMoveTime = currentMillis;
}
} else if (avl < avr) {
if (currentMillis - lastMoveTime >= moveDelay) {
servoh = servoh + 1;
if (servoh > servohLimitHigh) {
servoh = servohLimitHigh;
}
horizontal.write(servoh);
Serial.println("Rotating Right");
lastMoveTime = currentMillis;
}
}
}
delay(100); // Small delay between loops
}