I must be missing something

I have been at this for a few hours and I still have no idea why this is not working how I think it should.
What I am trying to do is have the LED turn on and stay if a switch is pressed, and turn off and stay off when it is pressed again. I know that there is an example that can do this much easier with less code but I wanted to try from the blink sketch adding each thing until I understood it.

Problem: The LED turns on and stays on but does not respond to hitting the switch again.

const int ledPin = 9;
const int switchPin = 10;
boolean lastButton = LOW;
int ledOn = false;
boolean currentButton = LOW;

void setup()
{
 pinMode(ledPin, OUTPUT);
 pinMode(switchPin, INPUT);
}

boolean debounce(boolean last)
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

 void loop()
 {
   currentButton = debounce(lastButton);
   if (lastButton == LOW && currentButton == HIGH && ledOn == false)
   {
     digitalWrite(ledPin, HIGH);
      lastButton = currentButton;
       ledOn = true;
   }
if (lastButton == LOW && currentButton == HIGH && ledOn == true)
   {
     digitalWrite(ledPin, LOW);
     lastButton = currentButton;
       ledOn = false;
   }
       
 }

Please don't get me wrong. I am not asking anyone to fix this code for me. I really just want to understand why it isn't working properly. Thanks in advance for any help you can offer

void loop()
{
currentButton = debounce(lastButton);

if (lastButton == LOW && currentButton == HIGH && ledOn == false)
{
digitalWrite(ledPin, HIGH);
lastButton = currentButton; // currentButton has to be HIGH so lastButton is now HIGH
ledOn = true;
}

if (lastButton == LOW && currentButton == HIGH && ledOn == true)
{
digitalWrite(ledPin, LOW);
lastButton = currentButton;
ledOn = false;
}
}

If lastButton is always left HIGH, there is no way for the second if to ever execute.

THANK YOU

I fixed the code and it now works. Just learning why it wasn't working was extremely helpful and in just a few minutes I was able to figure out how to get around it.

New code :slight_smile:

const int ledPin = 9;
const int switchPin = 10;
boolean lastButton = LOW;
boolean ledOn = false;
boolean currentButton = LOW;

void setup()
{
 pinMode(ledPin, OUTPUT);
 pinMode(switchPin, INPUT);
}

boolean debounce(boolean last)
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

 void loop()
 {
   currentButton = debounce(lastButton);
   if (lastButton == LOW && currentButton == HIGH)
   {
     ledOn = !ledOn;
   }
       lastButton = currentButton;
    if (ledOn == true)   
    {
digitalWrite(ledPin, HIGH);
    }
else
{
digitalWrite(ledPin, LOW);
}

 }

You are welcome. I'm glad you have it working.