Button in stepper motor loop

hallo I want to implement the Button in the loop, so that when it pressed the Motor stops. but it doesn't work as I want. could you please help with advice.

void loop() {
  button.loop(); // MUST call the loop() function first
  int btnState = button.getState();
  for(int x = 0; x < 500 ; x++){
    if (btnState==HIGH){
      digitalWrite(dirPin,HIGH);
      digitalWrite(stepPin,HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin,LOW);
      delayMicroseconds(1000);
    else { break;}}
  }

You need to read the button inside the for loop. The way that it is, once it enters the for loop, btnState will not change state.

hello ,
yes. that was the solution. I changed the code as following and it works now. many thanks for the great quick advice.

void loop() {
  for(int x = 0; x < 500 ; x++){
  button.loop(); // MUST call the loop() function first
  int btnState = button.getState();
    if (btnState==HIGH){
      digitalWrite(dirPin,LOW);
      digitalWrite(stepPin,HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin,LOW);
      delayMicroseconds(1000);}
    else { break;}
  }
  }

What is the purpose of the for loop?

if you have for example an emergency bottun which stop the motor when pressed.

You don't need the loop for that. Just an 'if'. You described what the program is for, not what the 'for' loop is for...

I am beginner with arduino. Ithought to use the for loop to move the motor. the if is integrated in the loop to check the button. is there another way

You already have the other way. Your loop is inside the Arduino loop function. Every time your loop completes after 500 iterations, it just starts again when loop() resumes. So you can just remove the 'for' loop. It does nothing.

I'm not posting the code because I want you to learn from it.

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