Stepper motor does not stop after pushing button

hello all. i'm new into this.
i understand that a "for" Statement loops forever. but how do i get the motor stopped after clicking the button again?

this is my code i'm using.

#include <ezButton.h>
#include <CheapStepper.h>

#define LOOP_STATE_STOPPED 0
#define LOOP_STATE_STARTED 1

ezButton button(2);  
int loopState = LOOP_STATE_STOPPED;

CheapStepper stepper (8, 9, 10, 11);

boolean moveClockwise = true;

void setup() {
button.setDebounceTime(50); 
}

void loop() {

  button.loop(); 

  if (button.isPressed()) {
    if (loopState == LOOP_STATE_STOPPED)
      loopState = LOOP_STATE_STARTED;
    else // if(loopState == LOOP_STATE_STARTED)
      loopState = LOOP_STATE_STOPPED;
  }

  if (loopState == LOOP_STATE_STARTED) {

         for (int s=0; s<4096; s++){
         stepper.step(moveClockwise);
         }
    }
}

A for loop doesn't loop forever, it loops until the condition is meet. In your case, it'll loop until s = 4095.

You might be better with a while loop. While(button.is pressed()) would loop only while the button is pressed.

thank you for your replay.
actually when i click the button, the motor runs (forever). i need it to stop then i click the button again. this does not work. it still moves.

Read the state of the button switch inside of the for loop. Use the break() function to exit the for loop if the switch is pressed.

Kudos for using code tags in your first post. Most new members have to be asked to read the forum guidelines and post properly.

Or you could add it to the condition.

for (int s = 0; s < 4096 and not button.isPressed(); s++) {

the button.isPressed() is only checked during that instatnt of time between when the for loop ends and loop() is invoked again.

test this by holding the button down

may need to check for the button being pressed inside the loop or not using a for loop and incrementing the idx and stepping the motor once each iteration of loop() and separately handling the wrap around

on the other hand ... why not just step the motor while loopState == LOOP_STARTED?

thank you all. i need to rethink my code and read more about it.
it does not stop. i think i've made a mistake with the function button.isPressed.

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