Servo Increment then hold at certain position until sensor threshold met

I am trying to increment a servo from 0 to 180 and hold at 180 until a sound sensor reads above a certain level. If the sound sensor reads above that level, I want the servo to return to 0, and the loop begins again.

my code is below, but my main question is how to hold the servo to increment the servo and then hold it at a desired position until a threshold is met.

Is this an example where millis() should be used? Hope my questions make sense. Gratitude in advance for your help.

//include Servo Library
#include <Servo.h>

//create servo object
Servo nServo;

//create variable to store servo position
int pos = 0;

//create analog sound sensor
int sound = 0;
int soundlevel = A0;
int val;

void setup() {
  
  // attach servo
  nServo.attach(9);
  
  //initialize serial communication
  Serial.begin(9600);
}

void loop() {

  //constantly check to see if threshold is met
  int val = analogRead(A0);
  Serial.println(val);
    
  //make servo increment from 0 to 180 by 20 degrees every 30 seconds then stay at 180 until sensor threshold is met
    if (val <= 200){
      for (pos = 0; pos <= 180; pos += 20)
      noahServo.write(pos);
      delay(1000);

    if (pos == 180 && val < 100){
      noahServo.write(180);
   
  }
  
     if (val > 200){
      noahServo.write(0);
  
     }

  }
  }

I suspect you have one of your } braces in the wrong place. My guess is that the one on line 46 should actually be on line 35

If you use the AutoFormat tool to indent your code consistently that sort of thing is easier to see.

...R

Thanks for the help, Robin2. I'll check my braces and start using the AutoFormat tool. Will let you know if that solves my issue.

NL

  //make servo increment from 0 to 180 by 20 degrees every 30 seconds then stay at 180 until sensor threshold is met
      for (pos = 0; pos <= 180; pos += 20)
      noahServo.write(pos);
      delay(1000);

That comment is rubbish. While the servo will increment from 0 to 180 in steps of 20 degrees, it will take only a few hundred nanoseconds to issue the instructions to do that to the servo. The delay() does NOT happen every 20 degrees.

For loops should ALWAYS have curly braces around the body.

The for loop has nothing to do with the servo then holding still.

PaulS' point is that the delay is not going to be part of the for-loop because of the lack of braces.