Pausing Fading with Button

I've written a program that is continuously fading up and down. What I'd like to do is that when I press the button, the fading pauses at the brightness that I pressed it at. Right now I have two if statements, one for if the button is pressed and one for if its not. I also messed around with using a while loop, but I can't figure it out. Currently, when I press the button it just fades all the way off and holds there. Not sure how I can get it to remember what the brightness was when the button was pressed and stop there, resuming at the same spot when I release the button. Thanks in advance.

Without seeing your program how can we help?

To make it easy for people to help you please use the code button </> so your code looks like this and is easy to copy to a text editor. See How to use the Forum

…R

You need to put your button reads and response within the loop that performs each step of brightness change.
You probably have it outside a loop that gets to complete before caring about your button.

Sorry about that! Here’s what I have currently!

int ledPin = 9;    // LED connected to pin 9
const int buttonPin = 2;
int buttonState = 0;
int fadeValue = 0;
void setup()  {
pinMode(9, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if(buttonState == LOW) { // if button isn't pushed
  // fade in from min to max in increments of 5 points: 
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
  // sets the value (range from 0 to 255): 
  analogWrite(ledPin, fadeValue);
  // wait for 30 milliseconds to see the dimming effect 
  delay(30);
  } 
  // fade out from max to min in increments of 5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { 
  // sets the value (range from 0 to 255): 
  analogWrite(ledPin, fadeValue);
  // wait for 30 milliseconds to see the dimming effect 
  delay(30);
  }
}
// hold the brightness if button is pushed
else if(buttonState == HIGH) {
  fadeValue +=0;
  analogWrite(ledPin, fadeValue);
}
}

You need to remove the FOR loops and allow loop() to do the repetition. That will allow you to check the button between each fade step and stop the fading whenever you want.

Also, for a responsive program it is not a good idea to use delay() as the Arduino can do nothing during the delay() period.

The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. It may help with understanding the technique.

Have a look at Using millis() for timing. A beginners guide if you need more explanation.

…R