Go Down

Topic: Button Toggle! (Read 571 times) previous topic - next topic

Sgt. William

Hey everyone!

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

if (digitalRead(sensor) == HIGH)
  {
  digitalWrite(Motor, HIGH);
  delay(500);
  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?

Grumpy_Mike

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

johnwasser

  Something like this will do the trick:

Code: [Select]

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;

  [...]
  }

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

James C4S

You might also be interested in the Button library:

http://www.arduino.cc/playground/Code/Button
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

Go Up