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