#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin(9600);
myservo.attach(18); // attaches the servo on pin 9 to the servo object
}
void loop() {
circularEaseInOut(0, 180, 2000); // Start from 0 degrees, go to 180 degrees in 1000 milliseconds
circularEaseInOut(180, 0, 2000);
}
void circularEaseInOut(int startAngle, int endAngle, int duration) {
int steps = 100; // number of steps for the ease-in-out motion
int delayTime = duration / steps;
for (int i = 0; i <= steps; i++) {
float t = float(i) / steps;
float easingFunction = circularEaseInOutFunction(t);
int currentAngle = startAngle + easingFunction * (endAngle - startAngle);
myservo.write(currentAngle);
Serial.println(currentAngle);
delay(delayTime);
}
}
// Circular ease-in-out function
float circularEaseInOutFunction(float t) {
t *= 2.0;
if (t < 1.0) {
return -0.5 * (sqrt(1.0 - t * t) - 1.0);
} else {
t -= 2.0;
return 0.5 * (sqrt(1.0 - t * t) + 1.0);
}
}
// Sine ease-in-out function
float sineEaseInOutFunction(float t) {
return -0.5 * (cos(3.14 * t) - 1.0);
}
// Exponential ease-in-out function
float exponentialEaseInOutFunction(float t) {
t *= 2.0;
if (t < 1.0) {
return 0.5 * pow(2.0, 10.0 * (t - 1.0));
} else {
t -= 1.0;
return 0.5 * (-pow(2.0, -10.0 * t) + 2.0);
}
}