Button Toggle!

Hey everyone!

In a simple button scenario I want to run a If sentence just once!

if (digitalRead(sensor) == HIGH)
digitalWrite(Motor, HIGH);
digitalWrite(Motor, LOW);

But when the button is HIGH it keeps looping so it turns into pulses. How do I get to run just once everytime the sensor goes high?

Test if the button is high and also if it were low last time.
button = digitalRead(pin);
if(button == HIGH && lastButton == LOW) {
lastButton = button;

Something like this will do the trick:

boolean buttonWasDown = FALSE;

void loop()
  if (digitalRead(BUTTON_PIN) == HIGH)
    if (!buttonWasDown)  // Button was not already down
      buttonWasDown = TRUE;
      [ Do the motor thing]
  else // Button is now up
    buttonWasDown = FALSE;


You might also be interested in the Button library: