#include <ESP32Servo.h> // Include library to control servos on ESP32
Servo servo; // Create a Servo object
// Servo settings
int servoPos = 90; // Start position (middle)
const int servoLimitHigh = 180; // Max servo angle
const int servoLimitLow = 0; // Min servo angle
const int servoPin = 10; // PWM pin connected to servo
// LDR (photoresistor) pins
const int ldrNorth = A0; // North sensor
const int ldrSouth = A1; // South sensor
// Servo movement tolerance
const int tolerance = 150; // Minimum difference between sensors to move servo
void setup() {
Serial.begin(115200); // Initialize serial monitor for debugging
servo.attach(servoPin); // Attach servo to the PWM pin
servo.write(servoPos); // Move servo to initial position
delay(1000); // Wait 1 second for servo to reach position
}
void loop() {
// Read analog values from LDRs (0–4095 on ESP32)
int northValue = analogRead(ldrNorth);
int southValue = analogRead(ldrSouth);
// Calculate difference between sensors
int difference = northValue - southValue;
// Print readings for debugging
Serial.print("North ADC: "); Serial.print(northValue);
Serial.print(" South ADC: "); Serial.print(southValue);
Serial.print(" Difference: "); Serial.println(difference);
// Only move servo if the difference is larger than tolerance
if (abs(difference) > tolerance) {
// Map the difference to a step size (1–5 degrees)
// Bigger difference → bigger movement
int stepSize = map(abs(difference), tolerance, 4095, 1, 5);
// Move servo left or right depending on which LDR is brighter
if (difference > 0) servoPos += stepSize; // North is brighter → move right
else servoPos -= stepSize; // South is brighter → move left
// Keep servo angle within limits
servoPos = constrain(servoPos, servoLimitLow, servoLimitHigh);
// Update servo position
servo.write(servoPos);
}
delay(50); // Small delay to reduce jitter and avoid moving too fast
}Loading
xiao-esp32-c3
xiao-esp32-c3