Pages: [1]   Go Down
Author Topic: Button Toggle!  (Read 555 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 13
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Manchester (England England)
Offline Offline
Brattain Member
*****
Karma: 639
Posts: 34725
Solder is electric glue
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 212
Posts: 8975
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

  Something like this will do the trick:

Code:
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;

  [...]
  }
Logged

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

Fort Lauderdale, FL
Offline Offline
Faraday Member
**
Karma: 71
Posts: 6144
Baldengineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

You might also be interested in the Button library:

http://www.arduino.cc/playground/Code/Button
Logged

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

Pages: [1]   Go Up
Jump to: