#include <Servo.h>

Servo myservo;  // create servo object to control a servo

const int ServoPin = 9;
const int ButtonPin = 8;
byte flag = 0;

void setup()
{
  pinMode(ButtonPin, INPUT_PULLUP);
  myservo.attach(ServoPin);  // attaches the servo on pin 9 to the servo object
}


void loop()
{
  static unsigned long lastTime = 0;
  static unsigned char lastButton = HIGH;

  if (millis() - lastTime > 30) {
  
    unsigned char theButton = digitalRead(ButtonPin);

    if (theButton != lastButton) {
      lastButton = theButton;
      if (!theButton) flag++;

      lastTime = millis();
    }
  }

  while (flag == 1)
  {
    for (int pos = 0; pos < 180; pos ++) // goes from 0 degrees to 180 degrees
    { // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    flag = 2;
  }

  while (flag == 3)
  {
    for (int pos = 180; pos > 0; pos--) // goes from 0 degrees to 180 degrees
    { // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    flag = 0;
  }
}