Turning LED Fade Loop On and Off with Press Button

Hi there! I'm trying to get an LED to start fading in and out with a button press, with another button press turning the LED off entirely. I've tried a few different avenues, but nothing's seemed to work. With my current build, the LED stays static unless you hold the button down, in which case it fades in and out. I'm not sure what to do, as it seems like any variables I use to try and trigger the "off" state also trigger the "on" state, and I can't seem to unentangle the two.
Any help would be much appreciated!

int run;
int button = 7;
int led = 3;
int brightness = 0; 
int fadeAmount = 5;
void setup()
{
   run = 0;
   pinMode(button, INPUT_PULLUP);
   pinMode(led, OUTPUT);
}

void loop()
{
   if(digitalRead(button) == LOW)
   {
      if(run == 0)
      {
          run = 255;
      }
      else
      {
          run = 0;
      }
   }

   if(run > 0)
   {
      analogWrite(led, brightness);
   brightness = brightness + fadeAmount;
   if (brightness == 0 || brightness == 250) {
      fadeAmount = -fadeAmount ;
   }
   
   delay(35);
   }
  
   while(run > 0)
   {
      if(digitalRead(button) == LOW)
      {
          run = 0;
      }
   }
}

Hello quinsanity

It seems to be a school assigment, isn´t it?

This is a common task that comes up from time to time.

Take the from search engine to get some ideas.

Have a nice day and enjoy coding in C++.

looks like the code is just handling the state of the button, whether it is on/off, so releasing the button returns to the previous condition.

don't you want to recognize a button pressed, that it's changed state and is pressed, and use that to toggle between states

but there is both the state and the transition to a state.

with the LEDs off in an OFF state, pressing the button enters a state where the LEDs are faded in and out, the FADE state. pressing the button again should both immediately turn the LEDs off and then return to the OFF state.

loop() should have just 2 blocks of code. your code has 3. the one block is your if(run > 0) {. the other is to monitor the button for state changes, butLst !-= but and being pressed, (LOW == but and setting run and turning off the LEDs. (of the if(run > 0) { else condition can turn off the LEDs).

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.