Arduino button press "if statement"

Hello everyone,
I wrote a code to control stepper movement with 2 buttons, one to turn clockwise and the other to turn counterclockwise... I'm using an Arduino uno and A4988 driver.

The issue that I'm facing is: right now if you keep pressing one of the two buttons the motor repeats the for loop making the motor spin continuously. I need to implement a code where even if the button is pressed it just moves the given steps and to make the motor move again you need to release and press again the button si that if it is kept pressed nothing happens.

How could I do that?
Thanks everyone!

const int dirPin = 2;
const int stepPin = 3;
const int button1Pin = 7;
const int button2Pin = 8;
const int stepsPerRevolution = 200;
int button1State = 0;
int button2State = 0;
int UP_led = 12;
int DW_led = 11;
int RS_led = 10;




void setup() {

Serial.begin(9600);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
pinMode(UP_led, OUTPUT);
pinMode(DW_led, OUTPUT);
pinMode(RS_led, OUTPUT);
}


void loop() {

 button1State = digitalRead(button1Pin);
 button2State = digitalRead(button2Pin);


 if (button1State == HIGH) {
  Serial.println("BTT 1 pressed DOWN");
   StepDOWN();
    Reset();
     digitalWrite(DW_led, HIGH);
      delay(500);
}



 if (button2State == HIGH) {
  Serial.println("BTT 2 pressed UP");
   StepUP();
    Reset();
     digitalWrite(UP_led, HIGH);
      delay(500);    
}
}




void StepUP() {

digitalWrite(dirPin, LOW);
for(int x = 0; x < 200 ; x++) //UP
{
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(1600);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(1600);


}
}

void StepDOWN() {

 digitalWrite(dirPin, HIGH);
 for(int y = 0; y < 5; y++)
{
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(1600);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(1600);

}

}

void Reset() {

digitalWrite(stepPin, LOW);
digitalWrite(dirPin, LOW);


}```

You need to detect when the button becomes pressed rather than when it is pressed
See the StateChangeDetection example in the IDE

As mentioned:

Example code and schematics in my state change detection for active low inputs tutorial. The tutorial shows using a switch connected to ground and using the internal pullups. Wiring to ground is a more popular switch wiring method.

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