Servo move to a location, then stop

I must withhold the Gold Cigar Award for the nice fish @ruilviana gave you in #15.

The delay is tots unnecessary. The if statement can just be

 if (digitalRead(ButtonPin) == LOW) flag++;

any bouncing or whatever the delay was in there for is more than taken care of because your while statements block. For some good time. 30 milliseconds is minor, but it does delay the onset of motion. In some cases any delay is bad - it makes sense to begin trying to avoid using it, no matter it makes little difference in this case.

But wait! There's more. Hold your finger down on the button and you get continuous sweeping back and forth.

If that's what you want, fine. If that just happened out of the code, not so fine.

Replace the if statement with a real edge detector and that'll fix you up.

Test code back from the wokwi simulator.

#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;
  }
}

Try it yourself. Also you have noticed by now that you might want to send the servo somewhere in your setup code. :expressionless:

@paulpaulson has an edge detector, but makes the usual mistake of delaying, hindering rapid response to the button. 20 milliseconds, no large deal. Until it is.

a7