The switch in this mechanism is triggered on and off by the notches on the half gear and this interaction allows the gear or servo to rotate. It does this by counting the times the switch is pressed, and once the switch is pressed by a certain number of notches, it will change direction and continue the trend.

Demo 2 Video
#include <Servo.h&gt; 
long randNumber;
const int SWITCH_PIN  = 2;
Servo myservo;
int count = 0;
int angle ;

void setup()
{
    Serial.begin(115200);
    Serial.println("Hello!");
    myservo.attach(9);
    randomSeed(analogRead(0)); 
    randNumber = int(random(20,160));
    angle = randNumber;
    myservo.write(angle);
    delay(1000);
}

unsigned long next_step = 0;
int speed = 5;
void poll_servo()
{
  if (micros() &gt; next_step) {
    next_step += 100000; //microsec
    angle += speed;
    angle = constrain(angle, 10, 170);
    myservo.write(angle);
  }
}
bool last_switch = false;
void poll_switch()
{
  bool now = digitalRead(SWITCH_PIN);
  if (now != last_switch) {
    last_switch = now;

    count +=1;
    if  (count &gt; 5) {
      speed = -speed; 
      count = 0;
      }
  }
}

void loop()
{
poll_servo() ;
poll_switch() ;
}