Reading value from sensor, start stepper motor (with accel and motorshield)

Hey all,

i am tinkering with an arduino equippet with the adafruit motorshield (the old first version).
I use a photodiode for a photoelectric barrier. As soon as something passes the barrier the stepper should start and accelerate for a given period of time.
The sensor readings are fine, the if / else works too and so does the motor shield and the acceleration. But the whole thing together does not work and i am just not good enough for finding the problem.
At the moment the stepper starts as soon as something enters the barrier and rotates if the object stays in there. Of course it should only trigger the start but i do not know how to do this. Furthermore this only works one time until i need to restart.

Thank you so much!

#include <AccelStepper.h>
#include <AFMotor.h>
AF_Stepper motor(200, 2);


int senRead = 5;            
int limit = 300;            


void forwardstep() {
  motor.onestep(FORWARD, SINGLE);
 
}
void backwardstep() {
  motor.onestep(BACKWARD, DOUBLE);
}


AccelStepper stepper(forwardstep, backwardstep);



void setup()
{


  stepper.setMaxSpeed(600.0);
  stepper.setAcceleration(900.0);
  stepper.moveTo(900);
  Serial.begin(9600);


}

void loop()
{
  int val = analogRead(senRead); //photodiode reading


  if (val <= limit)   {
   
  }   else if (val > limit)  { 
     
    stepper.run();

  }
    
}

Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you take a few moments to Learn How To Use The Forum.
It will help you get the best out of the forum in the future.
Other general help and troubleshooting advice can be found here.

You have to track elapsed time once you begin running. You will also have to stop the motor after however long you want to run

#include <AccelStepper.h>
#include <AFMotor.h>
AF_Stepper motor(200, 2);

const int senRead = 5;
const int limit = 300;

unsigned long startTime;
unsigned long runDuration = 5000UL;   // run for 5 seconds
bool isRunning;

AccelStepper stepper(forwardstep, backwardstep);

void forwardstep() {
  motor.onestep(FORWARD, SINGLE);
}

void backwardstep() {
  motor.onestep(BACKWARD, DOUBLE);
}

void setup() {

  Serial.begin(9600);

  stepper.setMaxSpeed(600.0);
  stepper.setAcceleration(900.0);
  stepper.moveTo(900);
  isRunning = false;
}

void loop() {
  int val = analogRead(senRead); //photodiode reading

  // check to see if we are running and for how long
  if ( isRunning == true ) {
    if (millis() - startTime >= runDuration) {
      // all done
      stepper.stop();
      isRunning = false;
    }
  }
  else {
    // not running so check sesor
    if (val > limit)  {
      stepper.run();
      startTime = millis(); // remember when we started
      isRunning = true;
    }
  }
}