Latching a momentry button

Dear All,

I’ve been trying to get to grips with latching a momentry button in code but I’ve not yet managed to understand it. I’ve been looking in to debouncing etc but I cannot quite relate what I’ve read in to my particular issue.

I’ve a stepper motor and a button (which seems to have been wired N/C as opposed to N/O) hence why my code (below) refers to LOW in place of HIGH etc.

What I want to do is to press the button, write its state in to a variable and run my stepper motor (using the AccelStepper library). Until the button is pressed again and then it will stop the motor and save a new button state, then if it is pressed again, start the motor again…

You get the idea.

My code below currently works but only if the button is held down. I know I’m missing bits of code but I can’t quite work it out.

P.S. This is not a school project!

//Control 1 stepper motor connected to a driver, run it as a DC motor running at 120 RPM.

#include <AccelStepper.h>

const int buttonPin = 2;     // the number of the pushbutton pin

int buttonState = 0;         // variable for reading the pushbutton status

int motorSpeed = 6400; //120 RPM at 200 steps per rev (notated in microsteps)
int motorAccel = 3200; //microsteps/second/second to accelerate

int motorDirPin = 8; //digital pin 8     < ===THIS IS A DIRECTION PIN
int motorStepPin = 9; //digital pin 9

//set up the accelStepper intance
//the "1" tells it we are using a driver
AccelStepper stepper(1, motorStepPin, motorDirPin);

void setup()
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP);

  //bits for the stepper motor speed and acceleration:
  //stepper.move(-192000); //move 192000 microsteps (should be 1 minute but currently seems to be 46 seconds)
  stepper.move(-1252175); // should be 5 minute


void loop()
  /*The code in this loop will detect if a button is pressed and if so, it will run the motor
  if it is pressed again it will turn off the motor.
  //read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is LOW:
  if (buttonState == LOW) {
    // turn stepper motor on:
  } else {
    // turn stpper motor off:

Check out the state change detection example. It will show how to do what you want.

Thank you I'll check that out.