Servo Push Button trouble.

Hello. I found this code.

int servoPin = 9;
int myAngle;
int pulseWidth;
int button = 2;                                //sets the button to pin2
int val = 0;                                    //sets the value to 0

void setup ()
{
  pinMode(servoPin, OUTPUT);
  pinMode(button, INPUT);                    //sets the push button as an input
  Serial.begin (9600);                        //sets serial to 9600 bits per second
}

void servoPulse(int servoPin, int myAngle)
{
  pulseWidth = (myAngle * 10) + 600;
  digitalWrite(servoPin, HIGH);
  delayMicroseconds(pulseWidth);
  digitalWrite(servoPin, LOW);
}

void loop()
{
  val = digitalRead (button);                                           //sets the value to the state of the button
  if (val==HIGH){                                                        //if the push button is pressed proceed with the for loop
    for (myAngle = 0; myAngle <= 180; myAngle++)        
    {
  val = digitalRead (button);                                        //Reads the button between every angle change
      if (val==LOW)                                                    //if the button is released, the angle goes back to 30
      {
        myAngle = 0;
      }
     servoPulse (servoPin, myAngle);
     delay (20);
    } 
    for (myAngle = 180; myAngle >=170; myAngle--)       //If the button is not released, the loop returns to 30 and continues
    {
      servoPulse (servoPin, myAngle);
      delay (20);
    } 
}
}

its works everything is allright, but problem is that, if button is not relesed its gets back to 0 and go again. What need to be changdet, to if servo reach 180 degrees, its stop until button is relesed?

Any reason for not using the servo library?

val = digitalRead (button);

Buttons (switches) bounce. You need to read up on de-bouncing buttons.

You also have this code:

if (val==HIGH){                                                        //if the push button is pressed proceed with the for loop
    for (myAngle = 0; myAngle <= 180; myAngle++)
    {
  val = digitalRead (button);                                        //Reads the button between every angle change
      if (val==LOW)                                                    //if the button is released, the angle goes back to 30
      {
        myAngle = 0;

If the button IS pushed, you read to see if the button is released. These reads occur within microseconds of each other. It’s not really likely that you can release the button within that time frame.

The button states should not be nested.

Read the state of the button. If it is HIGH, do something. Else, it is LOW, so do something else.