// Include the servo motor library
#include <ESP32Servo.h>
// Define the LDR sensor pins in the Analog pins
#define LDR1 15
#define LDR2 2
// Define the error value. This eliminates unnecessary movements
#define error 10
// Starting point of the servo motor
int Spoint = 90;
// Create an object for the servo motor
Servo turner;
void setup() {
// Include servo motor PWM pin
turner.attach(12);
// Set the starting point of the servo
turner.write(Spoint);
delay(100);
}
void loop() {
// Get the LDR sensor values
int ldr1 = analogRead(LDR1);
int ldr2 = analogRead(LDR2);
// Get the difference of these values
int errorCheck_1 = abs(ldr1 - ldr2);
int errorCheck_2 = abs(ldr2 - ldr1);
if ((errorCheck_1 <= error) || (errorCheck_2 <= error)) {
// They've become equal, hence, stay central
if (ldr1 = ldr2) {
Spoint = 90;
}
// No significant change, do nothing
} else {
if (ldr1 > ldr2) {
Spoint = Spoint + 1;
}
else if (ldr1 < ldr2) {
Spoint = Spoint - 1;
}
}
// Write values on the servo motor
turner.write(Spoint);
delay(50);
}