Setting number of loops for stepper

For the basic stepper sketch of one revolution in each direction, if one wants to have the loop repeat 5 times and then have the stepper stop, how should the code be done? I've tried using 'for' and just cannot get it right.

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 51.23 rpm:
  myStepper.setSpeed(51.23);
 
  }


void loop() {
  
 // step one revolution  in one direction:
    myStepper.step(stepsPerRevolution);
  delay(10);

  // step one revolution in the other direction:
    myStepper.step(-stepsPerRevolution);
  delay(10); 
  
}

Post your best effort and explain what is wrong with what it does

Use a counter variable, increment it by one with every loop cycle and don't call the step methods anymore if it reaches 5. Something like that (untested):

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int cycleCount = 0;

void setup() {
    // set the speed at 51.23 rpm:
    myStepper.setSpeed(51.23);

}


void loop() {
    if ( cycleCount < 5 ) {
        // step one revolution  in one direction:
        myStepper.step(stepsPerRevolution);
        delay(10);

        // step one revolution in the other direction:
        myStepper.step(-stepsPerRevolution);
        delay(10);
        cycleCount++;
    }
}

setSpeed takes a long integer, NOT a float (fractional number).
myStepper.setSpeed(51);

How is your motor connected to Arduino?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.