I’m a noob and I can’t figure out where I’m going wrong. My objective is to press the BUTTON once and have the LED start at 0 and go to 255 in brightness. Press the BUTTON again and have the LED go from 255 to 0.
When I run the code, each time I press the BUTTON, LED goes from 0 to 255. Never 255-0???
I’m sure I’m doing something silly. Thanks for your help!
Here’s my code:
const int LED = 9;
const int BUTTON = 2;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;
void setup() {
pinMode (LED, OUTPUT);
pinMode (BUTTON, INPUT);
}
/* Debouncing Function
* Pass it the previous button state
* and get back the current debounced state.
*/
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON);
if (last != current)
{
delay(5);
current = digitalRead(BUTTON);
}
return current;
}
void loop()
{
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
ledOn = !ledOn;
// digitalWrite(LED, ledOn);
//delay(1000);
if (ledOn = true)
{
for (int i = 0; i < 256; i++)
{
analogWrite(LED, i);
delay(2);
}
}
if (ledOn = false)
{
for (int i = 255; i >= 0; i--)
{
analogWrite(LED, i);
delay(2);
}
}
}
lastButton = currentButton;
}