Trouble with Toggling a Blinking LED

Hi All,

I am new to the Arduino community, so forgive me if I am asking my question in the wrong place. I am trying to toggle a blinking LED by pressing a button. To be clear, I want to press the button to make the LED blink, and then press it again to make it stop blinking. However, when I run my code, I need to hold down the button to make the LED blink. If anyone can help, I would greatly appreciate it.

const int led = 9;
const int button = 8;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

void setup()
{
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP);
}

boolean debounce(boolean lastButton)
{
currentButton = digitalRead(button); // reads the button
if (lastButton != currentButton) // if the current button state differs from the previous...
{
delay(5); //wait 5ms
currentButton = digitalRead(button); //read the button again
}
return currentButton;
}

void loop()
{
boolean currentButton = debounce(lastButton);
if (currentButton == HIGH && lastButton == LOW)
{
//ledOn = !ledOn;
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}
//lastButton = currentButton;
//digitalWrite(led, ledOn);
}

Use the button toggle to toggle a counting variable, then since there's only 2 'modes' of blinking or off, you can do an if else or a switch case.

You have commented out the line that saves the previous button state so it never changes in the program.

Please edit your code to have code-tags. See How to use the forum.

And after you detected a button becoming pressed you need to remember that (aka, put it in a variable) and only check that variable to see if you need to blink or not. So button only changes the variable and the blinking is ONLY controlled by that variable (not the button anymore)

And a note, your code is blocking because it uses delay(). Which means that if you pres and release the button while blinking it will not detect that. And the same for the debounce, it will block so it will add time to the loop aka the blinking. Instead of delay(), study millis() by looking at Blink without delay. And for the button, you could also make it easy for yourself and grab a library like Bounce2.