#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
void setup()
{
Serial.begin(115200); // Begin Serial Monitor
myservo.attach(ServoPin); // Set up ServoPin using Servo library
}
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
for (int i = angle; i <= 180; i += incrementRate)
{
angle = i;
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
for (int i = angle; i >= 0; i -= incrementRate)
{
angle = i;
myservo.write(angle);
Serial.print("Moving to ");
Serial.println(angle);
delay(sweepDelay); // Adjust delay for smooth movement
}
}
}
}