IR sensor only read once

New Bee Profile please bare me :confused:

Working on a project
Where all working fine but issue is want to run the if only once.
Till next detect happens

here’s flow
ir sensor detect >> relay > ON & OFF>> motor rotates ( works fine)
want to stop till next ir detects.

Using L298N , IR sensor & relay

Expert guide pls

//sketch created by chetuk
int motor1pin1 = 2;
int motor1pin2 = 3;
int IRSensor = 4;
int Relay = 13;

void setup(){
pinMode(IRSensor, INPUT); // sensor pin INPUT
pinMode(Relay, OUTPUT); // Relay IN
pinMode(motor1pin1, OUTPUT);
pinMode(motor1pin2, OUTPUT);
}

void loop()
{
  int statusSensor = digitalRead (IRSensor);
  if (statusSensor == 0){
    digitalWrite(Relay, HIGH);
    delay(1000);
    digitalWrite(Relay, LOW);
    delay(1000);
    digitalWrite(motor1pin1, HIGH);
    digitalWrite(motor1pin2, LOW);
    delay(2000);
    digitalWrite(motor1pin1, LOW);
    digitalWrite(motor1pin2, LOW);
    delay(2000);
  }
  else
  {
     digitalWrite(Relay, LOW);
  }
  
}

The state change detection example may have what you want. It shows how to detect changes (instead of levels). So the code can run just when the signal goes from 1 to 0 instead of is 0. And the change from 0 to 1 can be ignored.

Does this do what you want. It uses the method from the state change detection example.

//sketch created by chetuk
int motor1pin1 = 2;
int motor1pin2 = 3;
int IRSensor = 4;
int Relay = 13;

int lastStatusSensor = 1;

void setup()
{
   pinMode(IRSensor, INPUT); // sensor pin INPUT
   pinMode(Relay, OUTPUT); // Relay IN
   pinMode(motor1pin1, OUTPUT);
   pinMode(motor1pin2, OUTPUT);
}

void loop()
{
   int statusSensor = digitalRead (IRSensor);
   if (statusSensor != lastStatusSensor)
   {
      if (statusSensor == 0)
      {
         digitalWrite(Relay, HIGH);
         delay(1000);
         digitalWrite(Relay, LOW);
         delay(1000);
         digitalWrite(motor1pin1, HIGH);
         digitalWrite(motor1pin2, LOW);
         delay(2000);
         digitalWrite(motor1pin1, LOW);
         digitalWrite(motor1pin2, LOW);
         delay(2000);
      }
      lastStatusSensor = statusSensor;
   }
   else
   {
      digitalWrite(Relay, LOW);
   }
}