#include <ESP32Servo.h> // Allow ESP32 to control servo
Servo myservo; // Create Servo Object to control a servo
const int ServoPin = 23; // Setting pin 23 for servo
unsigned long ADC_previous_millis = 0;
const unsigned int ADC_interval = 100; // Interval to check ADC
int angle = 0; // Current angle of Servo
const unsigned int incrementRate = 2; // Increment rate
const unsigned int sweepDelay = 20; // Delay for smooth movement
const int maxAngle = 180; // Maximum angle for the servo
const int minAngle = 0; // Minimum angle for the servo
void setup()
{
Serial.begin(115200); // Begin Serial Monitor
myservo.attach(ServoPin); // Set up ServoPin using Servo library
myservo.write(angle); // Initialize servo to starting angle
}
void loop()
{
unsigned long current_millis = millis();
if (current_millis - ADC_previous_millis >= ADC_interval)
{
ADC_previous_millis = current_millis;
int ADC_value = analogRead(A5); // Variable to read the value from analog pin
Serial.print("ADC value now is ");
Serial.println(ADC_value);
if (ADC_value < 2500)
{
// Clockwise rotation: Move servo from current angle to 180 degrees
if (angle < maxAngle)
{
angle += incrementRate;
if (angle > maxAngle) angle = maxAngle; // Ensure angle does not exceed max
myservo.write(angle);
Serial.print("Moving to ");
Serial.println(angle);
delay(sweepDelay); // Adjust delay for smooth movement
}
}
else if (ADC_value >= 2500 && ADC_value < 4000)
{
// Counter-clockwise rotation: Move servo from current angle to 0 degrees
if (angle > minAngle)
{
angle -= incrementRate;
if (angle < minAngle) angle = minAngle; // Ensure angle does not go below min
myservo.write(angle);
Serial.print("Moving to ");
Serial.println(angle);
delay(sweepDelay); // Adjust delay for smooth movement
}
}
}
}