How to add one pushbutton to control stepper motor?

When I test following code, I hope it start to run after push button is pressed, but it always ran, means
push button didn't work at all? Can somebody check the code for me?

Thanks!

#define X_DIR     3       
#define X_STP     4       
int pushbuttonpin = 7;    //Pin for momentary push button switch or sensor
int val=0;

void step(boolean dir, byte dirPin, byte stepperPin, int steps)
{
  
  digitalWrite(dirPin, dir);
  delay(50);
  for (int i = 0; i < steps; i++) {
    digitalWrite(stepperPin, HIGH);
    delayMicroseconds(800);  
    digitalWrite(stepperPin, LOW);
    delayMicroseconds(800);  
  }
}
void setup(){

  Serial.begin(9600);
  pinMode(pushbuttonpin, INPUT);   //Declare push button switch pin as input
 
  pinMode(X_DIR, OUTPUT); pinMode(X_STP, OUTPUT);
    
}
void loop(){
  val=digitalRead(pushbuttonpin);
  if(val==HIGH)
  {
  step(true, X_DIR, X_STP, 800); 
    delay(1000); 
  step(false, X_DIR, X_STP, 400); 
 
}
}
pinMode(pushbuttonpin, INPUT);

You're not using the internal pull-up or pull-down resistors. Do you have external ones? Or do you have floating inputs?

if(val==HIGH)

You seem to have the switch wired backwards so that it reads HIGH when pressed. Normally one would wire the switch to read LOW when pressed so one could take advantage of the internal pull-up resistors built into the chip and avoid the need for external resistors.

yes, I have external resistor, How to change code? Thanks!

Richard905:
yes, I have external resistor

Show how you have them wired.

Richard905:
How to change code?

Who knows, we still can't see the circuit that goes with it.

Have you made sure that the button is not in floating state?

You have many delay() in your code. To allow the program to respond to the button pushed any time you must get rid of delay() and use millis() for timing

same as following example,

Richard905:
same as following example,
https://www.arduino.cc/en/Tutorial/Button

Then it would work. Show what you actually did, not the example you followed. Unless you just want me to try to debug the example. (nothing is wrong with it so I'm done in that case.)

Problem is solved! Connect GND of Arduino board to push button GND.

Thanks !