LDR controlled Servo- Controlling the Loop

Hi guys,

Trying to run a continuous servo for a specific amount of time based on a reading from the LDR. Purpose is to open a door if LDR reading is above specified condition and then close it if the reading is below specified condition. The values I have in there right now are just preliminary so that doesn't matter at the moment.

What I need: loop needs to run once for the first statement, and then stop until the second condition is met.

Problem: I think the problem is that it keeps looping and reattaching the servo even after the detach.

How can I make the loop run only once until the condition changes to above or below the specified value.

Side note: When I block the LDR it changes the condition. So I believe the only issue is controlling the loop only once, until the condition changes.

Here's the code:

#include <Servo.h>

Servo servo1;
  
void setup() {
 servo1.attach(9);
 
}

void loop() {
  int lightValue = analogRead(A0);
  if (lightValue < 600){
    servo1.attach(9);
    servo1.writeMicroseconds(1600);
    delay(1000);
    servo1.detach();
  } 
 else if (lightValue > 750){
  servo1.attach(9);
  servo1.writeMicroseconds(1000);
  delay(10000);
  servo1.detach();
 }

}

If I understand you correctly, you can use a flag that only allows the light low test if the light was previously high and vice versa.

Something like this

#include <Servo.h>

Servo servo1;
boolean lowLight = false;

void setup()
{
  servo1.attach(9);
}

void loop()
{
  int lightValue = analogRead(A0);

  if (!lowLight && lightValue < 600)
  {
    lowLight = true;
    servo1.attach(9);
    servo1.writeMicroseconds(1600);
    delay(1000);
    servo1.detach();
  }
  else if (lowLight && lightValue > 750)
  {
    lowLight = false;
    servo1.attach(9);
    servo1.writeMicroseconds(1000);
    delay(10000);
    servo1.detach();
  }
}