How to get a motor to work with a button

Hi,

I have been trying to get this to work for hours now. I need to push a button (and release instantly), make the motor run, until the motor hits another button.

Can anyone please help me with this?

Thank you

Here is an example using the method of the state change detection tutorial to toggle a motor on and off with one switch (button) and, if the motor is on, turn it off when a different switch is activated (limit). The switches are wired to ground with the internal pullups enabled.

const byte motorPin = 4;
const byte  buttonPin = 5;
const byte limitPin = 6;

boolean buttonState = 0;         // current state of the button
boolean lastButtonState = 1;     // previous state of the button
boolean motorState = 0;

void setup()
{
   Serial.begin(115200);
   // initialize the button pin as a input with internal pullup enabled
   pinMode(buttonPin, INPUT_PULLUP);
   pinMode(limitPin, INPUT_PULLUP);
   pinMode(motorPin, OUTPUT);
   digitalWrite(motorPin, LOW);
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 50;  // check switch 20 times per second
   if (millis() - timer >= interval)
   {
      timer = millis();
      // read the pushbutton input pin:
      buttonState = digitalRead(buttonPin);
      // compare the new buttonState to its previous state
      if (buttonState != lastButtonState)
      {
         if (buttonState == LOW)
         {
            motorState = !motorState; // toggle the motor state
         }
      }
      lastButtonState = buttonState;   // save the current state for later   
   }
   
   if(digitalRead(limitPin) == LOW && motorState == HIGH)
   {
       motorState = LOW; // motor off
   }
   digitalWrite(motorPin, motorState);
}