Stop code from looping

I’m trying to rotate a hobbico cs-60 servo from 0 to 90 degrees only once and I was wondering if there was any way to stop my code from looping. I’ve tried removing void loop but that didn’t work. I’ve checked the wiring and it’s all been put in correctly, so I’m guessing it’s a problem with the code. But I’m not getting any error messages.

Here’s my code:

 void setup()
{
  myservo.attach(9);  //attaches servo on pin 9 to servo object
}

void loop()

{
  delay(30);
  {
}
  for(angle = 90; angle < 180; angle += 1)  
  {                                         
 
myservo.write(angle);      
myservo.write (180-angle);  

delay(50);             
}
for(angle = 180; angle >=90; angle -= 1) // goes from 180 to 90 degrees
{
  myservo.write(angle);       
  myservo.write(180-angle);   

 while(1) {}
}
}

The first time I run it it works fine, but it keeps jerking back when I run the code again. Is it supposed to do that? And is there any way to stop that from happening?

Any help is appreciated!

    myservo.write(angle);
    myservo.write(180 - angle);

You are writing to the servo twice with different values and no delay between them so I would expect the servo to twitch as it executes the commands. Get rid of one of the write()s

   while (1) {}

The program will stop at this point but as it is in the for loop that will stop too. Move it outside of the second for loop.

Besides what Bob said, the two brackets after ‘delay(30)’ aren’t needed.

And do you really want that delay anyway? It just waits 30mS before doing anything, for no reason that I can see.

Finally, you don’t necessarily need this at all:-

while(1) {}

You could just put all of the code in ‘setup()’, and leave the loop empty:-

void loop(){}

Another way to make something happen once only is to use a variable to count how many times the code has run - something like this

void loop() {
   if (numRepeats <= maxRepeats) {
      // do stuff
      numRepeats ++;
   }
}

…R