This will do the sequence just once:
#include <Servo.h>
Servo Myservo; // create servo object to control a servo
const byte ServoPin = 3;
const int minAngle = 45;
const int maxAngle = 50;
int angle = minAngle; // initial angle
int angleStep = 10;
void setup()
{
// Servo button demo by Robojax.com
Serial.begin(9600); // setup serial
Myservo.attach(ServoPin); // attaches the servo on pin 3 to the servo object
Serial.println("Robojax Servo Button ");
Myservo.write(angle); //initial position
angle += angleStep;
Myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle); // print the angle
Serial.println(" degree");
delay(200); // waits for the servo to get there
angle -= angleStep;
Myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle); // print the angle
Serial.println(" degree");
delay(200); // waits for the servo to get there
}
void loop() {}
Here is the more complex version in case you ever want to change minAngle, maxAngle, or angleStep:
#include <Servo.h>
Servo Myservo; // create servo object to control a servo
const byte ServoPin = 3; //~
const int minAngle = 45;
const int maxAngle = 50;
int angle = minAngle; // initial angle for servo (beteen 1 and 179)
int angleStep = 10;
void setup()
{
// Servo button demo by Robojax.com
Serial.begin(9600); // setup serial
Myservo.attach(ServoPin);
Serial.println("Robojax Servo Button ");
Myservo.write(angle);//initial position
bool running = true;
while (running)
{
// change the angle for next time through the loop:
angle = angle + angleStep;
// reverse the direction of the moving at the ends of the angle:
if (angle >= maxAngle)
{
angleStep = -angleStep;
}
if (angle <= minAngle)
{
running = false;
}
Myservo.write(angle); // move the servo to desired angle
Serial.print("Moved to: ");
Serial.print(angle); // print the angle
Serial.println(" degree");
delay(200); // waits for the servo to get there
}
}
void loop() {}