Accelstepper move while button pressed

Hi, this code works fine for stepper movement. When button is briefly pressed, it moves the set amount with smooth ramp up and down curves.
But I wish to be able to hold button down and have it ramp up and keep motor at set speed until letting go of button which will ramp down motor to a stop. I’ve experimented and searched everywhere but no luck as yet.
Thanks if anyone can help.

#include <AccelStepper.h>
AccelStepper stepper(1,7,8);
int buttonPin = 2;
int buttonState = LOW;
 
void setup()
{  
stepper.setMaxSpeed(500);
stepper.setAcceleration(200);
stepper.setMinPulseWidth(100);
}
 
void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
if (stepper.distanceToGo() == 0) 
 
stepper.move(500); 
stepper.run(); 
}

You'll have to start thinking in terms of a state-machine - if this is unfamiliar now is the time
to learn...

To follow what @MarkT has said, you need to do things when the state of the button changes.

For example start the ramp-up when it goes from not-pressed to pressed and start the ramp-down when it goes from pressed to not-pressed.

...R

Thanks for your advice. This code will do the job but has a strange acceleration curve (seems to be somewhat incremental) but the de-acceleration is fine. It would be nice to have it working properly.
Any ideas as to what I’ve done wrong?

Thanks again.

#include <AccelStepper.h>
AccelStepper stepper(1,7,8);
int buttonPin = 2;
int buttonState;
 
void setup()
{  
stepper.setMaxSpeed(2000);
stepper.setAcceleration(200);
stepper.setMinPulseWidth(100);
pinMode(buttonPin, INPUT);
}
 
void loop()
{
    buttonState = digitalRead(buttonPin);
 if (buttonState == HIGH)
    stepper. move (20000);
    stepper. run ();
   
    buttonState = digitalRead(buttonPin);
 if (buttonState == LOW)

{ 
    stepper.stop();
    stepper.runToPosition();
}
}

flotchino:
Any ideas as to what I’ve done wrong?

You don’t seem to have taken any account of the advice.

As written your code acts WHEN the buttonState is HIGH. It should be working when it CHANGES from LOW to HIGH.

…R

Still learning, thanks for that powerful message.
I will keep trying to understand.

To detect change you must record the previous state so you can compare with the current state.