How to make a led light stay on when pressed once and off when pressed again

Here is example code using the state change detection method to use a push button to toggle the state of the built in LED (pin 13 on Uno).

// 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
boollastButtonState = 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;
   }
}

The Arduino tutorial uses an active high switch (high when pressed). A better way is to wire the switch as active low. The button switch is wired active low in the above code. See my tutorial on the state change detection method with an active low switch.

I also use the millis() for timing to make the code non-blocking. See these tutorials:
Several things at a time.
Beginner's guide to millis().
Blink without delay().

2 Likes