# use a push button as a toggle switch

**URL:** <https://forum.arduino.cc/t/use-a-push-button-as-a-toggle-switch/486589>\
**Category:** Programming\
**Created:** [October 19, 2017, 4:01pm UTC](https://forum.arduino.cc/t/use-a-push-button-as-a-toggle-switch/486589 "2017-10-19T16:01:55Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![LarryD](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/larryd/32/215550_2.png) [@LarryD](https://forum.arduino.cc/u/LarryD)\
**Post date:** [October 19, 2017, 4:31pm UTC](https://forum.arduino.cc/t/use-a-push-button-as-a-toggle-switch/486589/2 "2017-10-19T16:31:02Z")

</div>

See:  
[https://www.arduino.cc/en/tutorial/switch](https://www.arduino.cc/en/tutorial/switch)

```cpp
/* switch

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
  a minimum delay between toggles to debounce the circuit (i.e. to ignore
  noise).

  David A. Mellis
  21 November 2006
*/

int inPin = 8;        // the number of the input pin
int outPin = 13;      // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;          // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
unsigned long time = 0;          // the last time the output pin was toggled
unsigned long debounce = 200UL;  // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin,  INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce)
  {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

```

---

_[View the full topic](https://forum.arduino.cc/t/use-a-push-button-as-a-toggle-switch/486589)._
