How can I add order of movements? Please Help!

Good afternoon to everyone.
Please see the code that i have below. I have the stepper motor and sensor connected to my Arduino.
So every time when I’m blocking the signal from sensor(laser) my stepper is moving to one of my five positions. I want to make order of the movements. So if I stop the signal, to have movement 1.
Next time when I will stop the signal to have movement 2, and like that to movement 5. After movement 5, when i will block the signal, I want movement 1 again. So if someone can help, please do it. Thanks.

Here is my code: (I have relay module connected too, but please ignore it)

#include <AccelStepper.h>
#define relay1 11
#define enablePin 9
int motorSpeed = 600;
int motorAccel = 10000;
int motorDirPin = 12;
int motorStepPin = 13;
int laser = 7;
int detector = 6;
int homePos = 0;
int step1Dist = 200;
int step2Dist = 300;
int step3Dist = 400;
int step4Dist = 500;
int step5Dist = 600;
int delay1 = 2000;
AccelStepper stepper1(1, motorStepPin, motorDirPin);

void setup()  {
  pinMode(enablePin, OUTPUT);
  pinMode(laser, OUTPUT);
  pinMode(relay1, OUTPUT);
  digitalWrite(enablePin, HIGH);


void Step(int dist)  {
  digitalWrite(laser, HIGH);
  boolean val = digitalRead(detector);
    if (val == 0){
      digitalWrite(enablePin, LOW);
      digitalWrite(relay1, LOW);
      digitalWrite(relay1, HIGH);
        digitalWrite(enablePin, HIGH);

void loop() {

Please modify your post and use the code button </> so your code looks like this and is easy to copy to a text editor. See How to use the Forum

You need a variable to keep track of which state your system is in. So each time the beam is broken add 1 to the value. When the value exceeds 5 put it back to 0 or 1 (depending on the logic required).

Then the appropriate motor movement can be determined by the value of the variable.


Good evening Robin2.

The problem is that I don't have experience in programming (started 1 week ago to code), so I will need to find a way how to connect one for statement that will count each movement. So if you can, give me only some simple explanation( few rows of code), how I can connect the for statement with all movements.

Thank you.

Something like ...

prevBeamState = beamState;
beamState = digitalRead(beamPin);
if (beamState != prevBeamState and beamState == LOW) { // assumes LOW = beam broken
   stepCount ++;
   if (stepCount > 5) {
     stepCount = 0;


Good afternoon Robin2. Thank you very much about your reply. It was very helpful.

Best Regards!