How might I add a delay, close the servo and go to the start again? #include &lt;Servo.h&gt;
Servo myServo;

  const int piezo = A0;
  const int button = 2;
  const int yellow = 3;
  const int green = 4;
  const int red = 5;

  int knockVal;
  int buttonVal;

const int quietKnock = 10;
const int loudKnock = 100;

boolean locked = false;
int numberOfKnocks = 0;


void setup()
{
  myServo.attach(9);
  pinMode(yellow, OUTPUT);
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  digitalWrite(green, HIGH);
  myServo.write(0);
  Serial.println(&quot;The box is unlocked!&quot;);
}

void loop()
{ //start of loop
  if (locked == false)
  { //start of if1
    buttonVal = digitalRead(button);
    if (buttonVal == HIGH)
    { //Start of if2
      locked = true;
      digitalWrite(green, LOW);
      digitalWrite(red, HIGH);
      myServo.write(90);
      Serial.println(&quot;The box is locked!&quot;);
      delay (1000);

    }     //end of if2
  }      //end of if1

  if (locked == true)

  { //start of if3

    knockVal = analogRead(piezo);

    if (numberOfKnocks &lt; 3 &amp;&amp; knockVal &gt; 0)

    { //start of if4

      if (checkForKnock(knockVal) == true)

      { //start of if5

        numberOfKnocks++;

      }   //send of if5

      Serial.print(3 - numberOfKnocks);
      Serial.println(&quot; more knocks to go&quot;);

    }     //end of if4

    if (numberOfKnocks &gt;= 3)

    { //start of if6
      locked = false;

      myServo.write(0);
      delay(20);
      digitalWrite(green, HIGH);
      digitalWrite(red, LOW);
      Serial.println(&quot;The box is unlocked!&quot;);

    }   //end of if
  }   //end of if3
}           //End of loop

boolean checkForKnock(int value)
{ //start of boolean

  if (value &gt; quietKnock &amp;&amp; value &lt; loudKnock)

  { //start of if7

    digitalWrite(yellow, HIGH);
    delay(50);
    digitalWrite(yellow, LOW);
    Serial.print(&quot;Valid knock of value &quot;);
    Serial.println(value);
    return true;
  }   //end of if7
  else
  { //start of else
    Serial.print(&quot;Bad knock value &quot;);
    Serial.println(value);
    return false;
  }   //end of else
}     // end of boolean
if (buttonVal == HIGH)
{ //Start of if2
  locked = true;
  digitalWrite(green, LOW);
  digitalWrite(red, HIGH);
  myServo.write(90);
  Serial.println(&quot;The box is locked!&quot;);
  numberOfKnocks = 0;
  delay(1000);
}

I have added numberOfKnocks = 0 at this part of the code so your knock value goes to zero on locking it which will not open the lock again as soon as you lock it. The problem was that you did not change the numberoflnock value which remains same even after locking it so when the code loops back to the unlocking part it automatically unlocks it.
Hope this helps you.