Go Down

Topic: Button Toggle! (Read 674 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);
  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:

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:

Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131