Go Down

Topic: Button Toggle! (Read 1 time) previous topic - next topic


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: 1G2qoGwMRXx8az71DVP1E81jShxtbSh5Hp


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