Can ezButton library be used to break from loops?

I'd want to create a program where a button push will stop the rotation of a stepper motor. Using these test programs, when I use IR sensor as a trigger to break loops, it works:

const int IR = 3;
const int stepPin = 5;
const int dirPin = 6;
const int enPin = 7;
int x = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IR, INPUT);
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);  
}

void loop() {
  while(true){
    x++;
    Serial.println(x);
    if(digitalRead(IR)==LOW){
      break;
    }
  }
  delay(1000);
  while(true){
    digitalWrite(dirPin,LOW); //Changes the direction of rotation    
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
    if(digitalRead(IR)==LOW){
      break;
    }
  }
  delay(1000);
}

But it didn't work the same way when I use the ezButton library in place of IR sensor, the program stays on the x++ loop one:

#include <ezButton.h>
const int stepPin = 5;
const int dirPin = 6;
const int enPin = 7;
int x = 0;

//Button
ezButton PUSH(4);

void setup() {
  Serial.begin(9600);
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);  
  //Button
  PUSH.setDebounceTime(50);
}

void loop() {
  PUSH.loop();
  while(true){
    x++;
    Serial.println(x);
    if(PUSH.isPressed()){
      break;
    }
  }
  delay(1000);
  while(true){
    digitalWrite(dirPin,LOW); //Changes the direction of rotation    
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
    if(PUSH.isPressed()){
      break;
    }
  }
  delay(1000);
}

Are there any ways to make ezButton library usable for breaking loops? Or that it just can't? (then what'd be the other solution? of which if able, keep it concise)

PUSH.loop();

Add that statement inside both while loops.

It works, I guess, thanks. Do I need to still put the PUSH.loop() for the void loop() as a whole?

Not with the code you posted with the two while loops.

The PUSH.loop() function is where the debounced button state is checked. Typically, where you do not have a program designed with blocking while loops, you would check every pass in the main loop.

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