#include <Servo.h>

constexpr uint8_t SERVO_PIN {6};
constexpr uint8_t MSWITCH_PIN {7};
constexpr int SERVO_MIN_POS {0};
constexpr int SERVO_MAX_POS {90};

enum class Direction : int8_t {forward = 1, backward = -1};

Servo servo; 

uint16_t setServo(Servo &sv, uint16_t position, Direction step, uint16_t wait = 5) {
  sv.write(position); 
  position += static_cast<int>(step); 
  delay(wait);
  return position;
}

void setup()
{
  pinMode(MSWITCH_PIN, INPUT_PULLUP);
  servo.attach(SERVO_PIN); 
  servo.write(SERVO_MAX_POS);
}

void loop() {
  static uint8_t lastState {HIGH};
  uint8_t state = digitalRead(MSWITCH_PIN);
  if (state != lastState) {
    lastState= state; 
    int pos = servo.read();
    switch(state) {
      case HIGH:
        do { pos = setServo(servo, pos, Direction::forward); } while (pos <= SERVO_MAX_POS);
        break;
      case LOW:
        do { pos = setServo(servo, pos, Direction::backward); } while (pos >= SERVO_MIN_POS);
        break;
    }
  }
}