Animated christmas house

In addition to making the button switch active low (per @ wildbill you can use the state change detection method (and a tutorial for active low buttons) to toggle the state of a variable by pressing the switch once to turn on and the next press turns off and so on.

This demo code uses an active low button (wired to ground and an input set to INPUT_PULLUP) to toggle the state of the onboard LED on pin 13 (of an UNO). It just as well could toggle the state of a variable that toggles on, off, on, off, ...

// by C Goulding aka groundFungus

const byte  buttonPin = 4;    // the pin that the pushbutton is attached to
const byte ledPin = 13;       // the pin that the LED is attached to

bool buttonState = 0;         // current state of the button
bool lastButtonState = 0;     // previous state of the button

void setup()
{
   // initialize the button pin as a input with internal pullup enabled
   pinMode(buttonPin, INPUT_PULLUP);
   // initialize the LED as an output:
   pinMode(ledPin, OUTPUT);
   // initialize serial communication:
   Serial.begin(9600);
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 50;  // check switch 20 times per second
   if (millis() - timer >= interval)
   {
      timer = millis();
      // read the pushbutton input pin:
      buttonState = digitalRead(buttonPin);
      // compare the new buttonState to its previous state
      if (buttonState != lastButtonState)
      {
         if (buttonState == LOW)
         {
            // if the current state is LOW then the button
            // went from off to on:
            digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the output
         }
      }
      // save the current state as the last state,
      //for next time through the loop
      lastButtonState = buttonState;
   }
}
1 Like